Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does int's value change?

Tags:

c

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?

like image 438
Mike Scuderi Avatar asked Mar 03 '26 19:03

Mike Scuderi


1 Answers

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!

like image 92
Luke19 Avatar answered Mar 06 '26 09:03

Luke19



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!