Michael
Michael

Reputation: 92

Why is (n = 0) == 0?

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

Answers (5)

Doug Rollman
Doug Rollman

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

ChuckCottrill
ChuckCottrill

Reputation: 4444

Since n = 0 is an expression that performs an assignment, two things happen,

  • n is assigned value 0
  • expression n = 0 evaluates to 0

This 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

S.S. Anne
S.S. Anne

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

Ente
Ente

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

Alberto
Alberto

Reputation: 12939

This instruction

if (n = 0) printf("a \n");

will do 2 things:

  1. assign 0 to n

  2. '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

Related Questions