Home > Enterprise >  Strange behaviour in C when comparing 2 values with "or" and "?" operator
Strange behaviour in C when comparing 2 values with "or" and "?" operator

Time:05-24

I have some code in an old desktop app, which I inheritted from a colegue who left the company. Here is a short similar example of the actual code I have:

#include <iostream>
int getType(int type)
{
    return type;
}

int main()
{
    int variable1 = 30;
    int variable2 = 40;
    int result = (getType(30) == (variable1 || variable2) ? 1 : 2);
    std::cout << result << std::endl;
}

For the result I always receive 2, not 1 as I expected. If I try:

int result = (getType(30) == (variable1) ? 1 : 2)

the result is true.

I can't figure out why this part:

int result = (getType(30) == (variable1 || variable2) ? 1 : 2)

is not true...

CodePudding user response:

In the initializer expression of this declaration

int result = (getType(30) == (variable1 || variable2) ? 1 : 2);

the subexpression (variable1 || variable2) has the type bool and its value is true (variable1 isn't 0 so that is true) that is implicitly converted to the integer value 1 in the expression with the equality operator (getType(30) == (variable1 || variable2) .

From the C 17 Standard (7.6 Integral promotions)

6 A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.

So as getType(30) is not equal to 1 the result of the initializer expression is 2.

To get the expected result you should rewrite the declaration like

int result = (getType(30) == variable1 || getType(30) == variable2) ? 1 : 2;

CodePudding user response:

I think perhaps your understanding of the || operator is not quite right. The || operator is the or operator, and it will return a boolean result, false or true. In your code, you are doing this comparison: getType(30) == (variable1 || variable2). The parenthesis get evaluated first because of order of operations and you end up with getType(30) == true, since variable1 has a non-zero value. getType(30) evaluates and returns 30, so the expression is 30 == true. The true value then gets coerced to a 1 because of the rules of c and we evalate 30 == 1 which is false.

I think what you are asking for is why this doesn't do what you expect. And I see two problems, the one is that the getType function doesn't actually do what you might expect, it simply returns the variable. I'm not sure what you would expect in c , but that's definitely a problem. The other expectation is probably that you want to compare the return of getType(30) with both variable1 and variable2 which would require a longer expression. The expression you want is probably getType(30) == variable1 || getType(30) == variable2. This is a common problem because in english we say 'if gettype equals var1 or var2`, but it doesn't translate into code like that unfortunately.

  • Related