Mike Scuderi
Mike Scuderi

Reputation: 37

Why does int's value change?

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?

Upvotes: 2

Views: 304

Answers (5)

Nikhil
Nikhil

Reputation: 6643

if (a = 0) 

In the above if statement, first 0 is assigned to the variable a. Then the condition is evaluated.

Because a now holds the value 0, it is evaluated as false and the corresponding else block is executed.

In C language, true is represented by any numeric value not equal to 0 and false is represented by 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?

Because, after execution of the first if statement, value of a is 0. So, when second if statement is evaluated, a has the value 0, and thus the condition if (a == 0) evaluates to true.

Upvotes: 2

Luke19
Luke19

Reputation: 362

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!

Upvotes: 12

Alessandro Mautone
Alessandro Mautone

Reputation: 883

in if (a = 0) your assigning value 0 to a.

To do a comparison you should do in if (a == 0) (so with double ==)

Upvotes: 2

RogerVieiraa
RogerVieiraa

Reputation: 92

in the first if you need to use "==".

if(a == 0) {

Upvotes: 5

RasmusW
RasmusW

Reputation: 3461

0 is false, ie. not true.

That is why the first if-statement behaves like it does.

And a=0 assigns 0 to a, which is the reason for its value afterwards.

Upvotes: 1

Related Questions