Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Incrementation not updating variable value

I am working on a simple C program, but ran in to some confusion. Below is the code:

int main(void) {
  int i, j, k;
  i = 3;
  j = 4;
  k = 5;

  printf("%d ", i < j || ++j < k);
  printf("\n");  // LINE 1

  printf("%d %d %d", i, j, k);  // LINE 2

  return 0;
}

In the above program, the variable j starts off being 4. Then in the printf statement of line 1 we increment the value of j by 1(++j = 5).

So theoretically, I would assume that when j is printed in printf(line 2) it prints as 5, since we did an incrementation in line 1 for j. However, every time I run the code, line 2 prints the original value of j which was 4, and NOT 5.

Is there something I am missing?

like image 522
sye Avatar asked Mar 14 '26 05:03

sye


1 Answers

j is never incremented because ++j is never evaluated. The OR operator is satisfied when it first checks i < j.

like image 107
Joshua Schlichting Avatar answered Mar 15 '26 21:03

Joshua Schlichting



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!