1

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'?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
just_chilling
  • 13
  • 1
  • 2
  • @Jabberwocky Operator precedence and associativity doesn't have anything to do with it. [What is the difference between operator precedence and order of evaluation?](https://software.codidact.com/posts/278172) – Lundin Nov 09 '21 at 07:50
  • @Lundin I stupidly mixed up associativity with order of evaluation. I delete this stupid comment including this one, thanks. – Jabberwocky Nov 09 '21 at 07:53

1 Answers1

1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335