0

I am aware that when a non zero value is provided as a condition in an if statement, the condition is evaluated to be true.

Yet, I'm wondering how an assignment(=) is evaluated to be true here, instead of a comparison(==), and runs without any errors in the below C program.

int main(){
int a, b =5;

if(a=10) {
   ("This works");
}

if(b=1){
   ("This works too");
} }
YUMI
  • 94
  • 9

2 Answers2

1
  1. a = 10 is an expression that assigns 10 to a and whose value is the result of the assignment (that is 10).

  2. any value different from 0 is considered to be true

Try this:

if (b = 0) {
   ("This is never displayed");
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
1

The assignment operator always returns the value that was assigned. So in your case a=10 has the value 10 and the if statement is essentially if(10). Which is true.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131