Reputation: 29
I am a college student who is taking his first programming class, in the process of studying a past exam I found this question:
give the following values of the print function
#include <stdio.h>
int main(){
float x;
int a = 5, b = 0;
x = a&b ? 2/8.f*5+b++ : a|b
printf("%f\n", x);
}
The printf displays 5.000 after running. What is tripping me up is the ?: operator. As I understand it, it works almost like an if, else statement, where if (condition) is true, then x, if not true then y. I don't understand the flow of the function.
is it saying that because the a&b yields 0 that it is not true, therefore x = a|b which after the operator runs yields decimal value 5?
Upvotes: 2
Views: 65
Reputation: 123578
is it saying that because the a&b yields 0 that it is not true, therefore x = a|b which after the operator runs yields decimal value 5?
Yup.
The expression parses out as follows:
(a & b) ? ((2 / 8.f) * 5 + (b++)) : (a | b)
&
is the bitwise AND operator; it will perform an AND operation on each bit of the two operands. Since a
is 5 (101
) and b
is 0 (000
), the result of a&b
is 101 & 000 == 000
.
Since a&b
evaluates to 0, the expression following the ?
is not evaluated; instead, (a|b)
is evaluated. |
is the bitwise OR operator. 101 | 000 == 101
, which is 5.
Hence your result.
Upvotes: 2
Reputation: 4203
Your understanding is exactly correct. The operator is called the ternary operator. In this case, the code evaluates a&b
to be 0
or false, which causes it to use the value after the :
, or a|b
, which is 5
. If, instead, b
were to equal 1
for example, then a&b
would evaluate to true, and x
would equal the expression before the :
, which evaluates to 2.25
.
Upvotes: 2