How Chen
How Chen

Reputation: 1370

if-else condition in C

In C language, what is the result of x=0 if I put it in if-else condition? if it is represent false or if this assignment is finished, then represent true?

my colleague write code as:

if(condition = 0)
{
    //do process A
}
else
{
    // do process B
}

obviously, this code is wrong, I know it should be condition == 0 or ((condition=foo()) == 0) but my assumption is program should always do process A because i think if(condition = 0) should always return true since this is set value 0 to variable condition and this set process should be true. However, program always do process B, that means if use the variable condition value and my assumption is wrong.

Then I did a another test code:

if(condition = 2) //or other none-zero value
{
    //do process A
}
else
{
    // do process B
}

this time, program always do process A.

My question is why if-else condition does not use the operation value of condition but use the left variable after setting?

Upvotes: 2

Views: 2707

Answers (3)

MD. Khairul Basar
MD. Khairul Basar

Reputation: 5110

when you assign 0 to variable condition it becomes false as 0 represents false and any non-zero value represents true.so, when you assign 0 else condition is executed and when you assign 2 condition represents a true statement so, it executes...

if(condition = 0)    

after assigning value 0 to condition it becomes

if(condition)    

and as it is false, it doesn't execute.but, when condition = 2, it works in the same way and become true .so, the if condition is executed then.

Upvotes: 4

George Eco
George Eco

Reputation: 462

You use wrong operator.

a = 10;

The "equals" operator means "assign value to".

Now to compare two operands, a and b, to see if a = b, you use another operand. That operand is double equals (==).

if(variable == 0)
{
    //do process A
}
else
{
    // do process B
}

Now look.

If the variable with name "variable" has value = 8 that is not equal to 0, thus the whole "variable == 0" expression if FALSE. So proccess B will run.

If otherwise variable is equal to 0 indeed, proccess A will be executed because "variable == 0" is true.

It's like:

if(EXPRESSION)
{
    // EXPRESSION IS TRUE
}
else
{
    //EXPRESSION IS FALSE
}

Got it? :)

Upvotes: 3

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26539

In C, assignment is an expression that returns the set value; i.e. x = 2 will result in 2.

This allows you to do something like this:

unsigned char ch;
while((ch = readFromFile(f)) != EOF) {
    // do something with ch
}

It also allows you to shoot yourself in the foot if you accidentally mistype == as =, which is why this 'feature' doesn't appear in a lot of other languages.

In your first loop, the expression condition = 0 will always result in 0, causing the else branch to be taken. Similarly, condition = 2 results in 2, which causes the true branch to be taken.

Upvotes: 2

Related Questions