Why does int's value change?

  • A+
Category:Languages

I have this C code:

int a = 5; printf("a is of value %d before first if statement. /n", a); if (a = 0) {     printf("a=0 is true. /n"); } else{     printf("a=0 is not true. /n"); } printf("a is of value %d after first if statement. /n", a); if (a == 0){     printf("a==0 is true. /n"); } else{     printf("a==0 is not true. /n"); } return 0; } 

output:

a is of value 5 before first if statement. a=0 is not true.  a is of value 0 after first if statement.  a==0 is true.  Program ended with exit code: 0 

I do not understand why the int value is still recognized as 5 in the first statement, but changes to 0 before the 2nd if, or why it changes at all?

 


When you do if (a = 0) you are setting the variable a to 0. In C, this will also evaluate the expression to 0.

So actually that if-statement works in two steps. It's as if you did:

a = 0; //assign 0 to a  if (a) {  ... } //evaluate a to check for the condition 

In which case, since a is 0, it evaluates to false. That's why you end up in the else of the first part, and in the second part (a == 0) evaluates to true!

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: