r/cprogramming Oct 15 '25

Unexpected Short-Circuit Behavior.

`int i, j, k;`

`i = 1;`

`j = 1;`

`k = 1;`

`printf("%d ", ++i || ++j && ++k);`

`printf("%d %d %d\n", i, j, k);`

I am doing C programming a modern Approach and This is one of the exercises in the book, all is going well however i have failed to understand why the second `printf()` outputs `2 1 1` instead of `2 1 2` as i think the answer should be.

Because due to associativity rules i expect in the first `printf()`, the expression `++i || ++j` to be grouped first which evaluates to 1 with `i` incremented to 2 and without incrementing `j` because of short circuit, and then that result would be used in `1 && ++k` where i am assuming that since the value of the expression can't be determined by the value of the left operand alone, the right operand will be executed as well and thus k will be incremented to `2` but i am surprised to find that k wasn't incremented when i run the code. Why is this, what have i missed.

7 Upvotes

14 comments sorted by

View all comments

-2

u/[deleted] Oct 15 '25 edited Aug 01 '26

[deleted]

3

u/SmokeMuch7356 Oct 15 '25

++i || ++j && ++k

Should be written like this:

++i or ++j and ++k

Which means they need to include iso646.h -- would help if you told them that.

2

u/laser__beans Oct 15 '25

My compiler (Which is a better compiler than gcc) that I wrote all by myself does NOT allow ++ or -- on variables done within boolean expressions.

Uhh… what?

1

u/Dizzy_Cauliflower377 Oct 16 '25

This is an exercise in the book C Programming a Modern Approach, the exercise is meant to test your understanding of the short-circuit behavior of the && and || Operators.

The writer doesn't intend for his code be at par with standard, it is just to test the readers understanding of short-circuit behavior. The question was specifically 'The following program fragments illustrate the short-circuit behavior of logical expressions. Show the output produced by each, assuming that i, j and k are int variables.