rolory rolory - 17 days ago 5
C Question

What does '-' do as a boolean expression

What I generally wanted to do is to check when

(x-3) > i
.


I got the following code:

int main()
{
int x = 10, i;

for(i = 0; i < 15; i++) {
if(x-3)
printf("%d, ", x);

x--;
}

return 0;
}


I accidentally wrote
(x-3)
instead of
(x-3 > i)
, and I got these results:

10, 9, 8, 7, 6, 5, 4, 2, 1, 0, -1, -2, -3, -4,


The number 3 is missing. I understood that it is something that somehow connected to the
x-3
expression, but I haven't find a clear answer yet in Google..


Does anyone have an idea? Thanks...

Answer

It just means the substruction operator.:)

According to the C Standard (6.8.4.1 The if statement)

2 In both forms, the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0. If the first substatement is reached via a label, the second substatement is not executed.

In this if statement

 if(x-3)

expression x - 3 always evaluates to non-zero value except when x is equal to 3.

So when x is not equal to 3 this statement

printf("%d, ", x);

is executed and outputs the current value of x.

When x is equal to 3 this statement is skipped.

The result demontsrates this explicitly

10, 9, 8, 7, 6, 5, 4, 2, 1, 0, -1, -2, -3, -4
                    ^^^ 3 is absent

The loop iterates 15 times but outputs only 14 values of x. The value of x equal to 3 is skipped due to the expression in the if statement.

Comments