Click here to Skip to main content
15,884,838 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
in the given c programs what's the process takes place at assignment and equality operators?

What I have tried:

#include <stdio.h>
void main()
{
int x = 0;
if (x = 0)
printf("Its zero\n");
else
printf("Its not zero\n");
}
OUTPUT:Its not zero

#include <stdio.h>
void main()
{
int x = 0;
if (x == 0)
printf("Its zero\n");
else
printf("Its not zero\n");
}
OUTPUT:Its zero
Posted
Updated 24-Dec-17 2:37am

x = 0 sets the value of x to 0, whereas x == 0 is 'true' if x equals 0.

Let's take a look at your if statement in the first code block:
C
if (x = 0)
x = 0 sets the value of x to zero, but this expression has the new value of x (thus zero) as return value. So this if statement is equivalent to if (0) (with the additional effect that the value of x gets set to zero). 0 maps to false (all other integers map to true), so the else block gets executed.

In your second if block:
C
if (x == 0)
x == 0 is true, so the if block gets executed.
 
Share this answer
 
v3
Comments
Venkatesh Pyla 24-Dec-17 7:06am    
Thanks for your smart answer.
Thomas Daniels 24-Dec-17 7:07am    
You're welcome!
[no name] 24-Dec-17 7:37am    
Indeed a smart answer! This because it explains a lot in about three sentences and this in a very clear way. Have my small 5 for this.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900