Reputation: 92
Can somone please explain me whats the reason behing this code and why does it print b
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
n = 0;
if (n = 0)
printf("a \n");
else
printf("b \n");
return 0;
}
Upvotes: 1
Views: 543
Reputation: 35
It's because of the line:
if (n = 0)
A single =
is used for assigning variables. ==
is how you compare equality in c.
So if you replace
if (n = 0)
with
if (n == 0)
then you should get "a" as your output
Upvotes: 1
Reputation: 4444
Since n = 0
is an expression that performs an assignment, two things happen,
n = 0
evaluates to 0This is why some advise writing comparisons as,
if( 0 == n ) print("a\n");
So that =
cannot accidentally be used when ==
was intended.
And why some compilers warn to write assignments (where you want both behaviors) as,
if( (n = 0) ) print("a\n");
Upvotes: 1
Reputation: 15576
This is not an equality check, but an assignment.
The expression n = 0
evaluates to the value of the right-hand expression (or 0
). Since 0
is considered false, the first condition is skipped and b
is printed.
What you really wanted to do was this:
#include <stdio.h>
int main(void)
{
int n = 0;
if (n == 0) /* notice: == */
printf("a \n");
else
printf("b \n");
return 0;
}
Here ==
, the equality operator, is used.
Upvotes: 2
Reputation: 2462
Because:
(n = 0) == 0
The =
is the assignment operator in C, which assigns 0
to n
and evaluates to the value being attributed. In this case 0
.
Upvotes: 1
Reputation: 12939
This instruction
if (n = 0) printf("a \n");
will do 2 things:
assign 0 to n
'return' 0 from the assignment (this is the reason behind multiple inline assignment like a = b = c
: b = c
will first assign to b the value of c, and than this will return the value of c, which will be also assigned to a)
Because of the second point, that instruction is the same of
if (0) printf("a \n");
And in C the 0 is evaluated as false, so this is the reason behind the printing of b
instead of a
.
Take in mind that the equal operator
in C and in most of the languages is ==
, where instead =
is the assigning operator, so if you want to check is n
is 0 you should have done this:
if (n == 0)
printf("a \n");
else
printf("b \n");
Upvotes: 3