Search code examples
coutputcompound-assignment

Compoud operator (+=) and && in C, weird value


Looking at this code:

#include <stdio.h>
#include <stdlib.h>

int main(){
  int a = -1;
  int b = 0xfc; // = 252
  b+=a && a++;
  printf("%d %d\n", a, b);
}

the output I think should be is:

0 251

Actually, the real output is:

0 253

But why? associativity of && is from left to right, so

  1. b = b - 1(a) (and b should be 251)
  2. the left part is true so: a++ (a = 0)

There's something wrong with my hypothesis, can someone explain to me what?

If can help that the output of gdb (with watchpoints to a and b):

Old value = 0
New value = -1
main () at test.c:7
7         int b = 0xfc;
(gdb) c
Continuing.

Hardware watchpoint 2: b

Old value = 0
New value = 252
main () at test.c:8
8         b+=a && a++;
(gdb) c
Continuing.

Hardware watchpoint 3: a

Old value = -1
New value = 0
0x0000555555555172 in main () at test.c:8
8         b+=a && a++;
(gdb) c
Continuing.

Hardware watchpoint 2: b

Old value = 252
New value = 253
main () at test.c:9
9         printf("%d %d\n", a, b);

Solution

  • The explanation is very simple.

    a && a++ is a logical operation and its result can be 0 or 1. As a is non zero and any non zero value is considered as the true the result of this operation is 1.

    This value is added to 252. The result displayed is 253.