cfor-loopoperatorsoperator-precedencelogical-and

Is the order of evaluation of AND operator from left to right guaranted?


I was studying the K&R "The C Programming Language" 2nd Edition book and in chapter 1.9 Character arrays on Page 29 there is an example program given to print out the longest line after reading a set of lines. In the program there is an example getline() function provided and within that function is a for loop that read characters and checks for validity and adds it to a character array if valid. The for loops is given as

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
        s[i] = c;

My question is: What guarantees (c = getchar()) != EOF is evaluated before c != '\n'?

Of what I previously know of C, order of associativity is not same as order of evaluation, and the C standard does not specify order of evaluation. If so what happens if c != '\n' is evaluated before (c = getchar()) != EOF? It should check newline character with previous character rather than the currently read character since the getchar() operation is done after the check of newline character, right?

A quick google search shows that this kind of code is commonly written, so I suspect it will work if I try it myself. Also the book claims all example programs are working programs.

What guarantees the evaluation of (c = getchar()) != EOF before c != '\n'?


Solution

  • According to the C Standard (6.5.13 Logical AND operator)

    4 Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.