Shrijan Regmi
Shrijan Regmi

Reputation: 427

What value is returned by "==" operator?

#include <stdio.h>
#include <conio.h>

void main() {
    int a, b, val;
    
    a = 5;
    b = 6;
    
    val = a == b;
    
    printf("The value is::: %d", val);
    
    getch();
}

I have a basic c-program above. Here the value of variable "val" will be 0 because a is not equals to b and the output is printed as "The value is::: 0".

My question is whether I can use this syntax in c-programming or not? Actually my teacher is arguing that the value won't be 0 or 1. I displayed him the output and now he is saying that I cannot use this in c-programming. Is this true ?

He says that a==b won't give 0 or 1 based on the values of a and b.

Upvotes: 0

Views: 93

Answers (1)

ivan.ukr
ivan.ukr

Reputation: 3581

As mentioned in the comments above by David C. Raskin, the standard clearly says that result of the == is int with value either 0 or 1. So the code is pretty legitimate and produces expected resulting value, and so your teacher seems to be wrong. On the other hand, if the entire purpose of that code is to assign initial zero value to the variable, it is not best code, and in this sense your teacher is right. Good code should be readable and clearly express what you want to do, and in such case, it is just better to have val=0.

Upvotes: 1

Related Questions