What will be the output of the following code snippet?
#include <stdio.h>
int main() {
float x = 5;
if (x > 10)
printf("Greater");
else if (x = 10)
printf("Equal");
else
printf("Smaller");
return 0;
}
Explanation
This code demonstrates a common pitfall in C programming regarding the difference between the equality operator (==) and the assignment operator (=).
Initialization: The variable x is initialized to 5.0.
First if condition: (x > 10) is (5 > 10), which is false.
Second if condition (the else if): The code evaluates (x = 10).
In C, this is an assignment operation, not a comparison.
The value 10 is assigned to x.
The result of an assignment expression is the value assigned (i.e., 10).
In C, any non-zero value is treated as true.
Execution: Since the expression (x = 10) evaluates to 10 (which is true), the program enters the if block and executes printf("Equal");.
The logic can be represented as:
Expression Evaluation⟹(x=10)=10=0⟹True
Result=Print "Equal"
Because the assignment evaluates to a non-zero (true) value, the "Equal" branch is executed, confirming that understanding operator precedence and usage is critical in C programming.