Reputation: 4571
I have the following line in my code:
1 || printf("A");
I was surprised to see that A is not printed; I am guessing this is due to compiler optimizations: 1 was evaluated as true, and, because the entire OR expression must have been true, the printf("A")
wasn't even evaluated... Can someone confirm this? Would the program behave like this with different compilers?
Upvotes: 0
Views: 94
Reputation: 10430
I am guessing this is due to compiler optimizations: 1 was evaluated as true, and, because the entire OR expression must have been true, the printf("A") wasn't even evaluated..
The decision to execute the printf("A")
function or not is not made during compilation but it is made during execution of the program. So, this rule out your explanation of compilation optimization
.
In the expression exp1 || exp2
, exp1 is evaluated first. If it evaluates to true
, then exp2
is not evaluated as result of logical operator is true
in-spite of the value of exp2
. However, if exp1
is false, then exp2
will be evaluated. This behavior is mandated by the standard.
So, in the expression 1 || printf("A")
, there is no need to evaluate printf("A")
as the result of the expression will be true
in-spite of the evaluation of printf("A")
due to the first expression which is 1
.
Similarly, expressions are evaluated(from left to right
) when logical AND operator &&
is used in between two expressions.
Upvotes: 0
Reputation: 370102
In the expression a || b
, b
is only evaluated when a
is false (similarly in a && b
, b
is only evaluated if a
is true
). This is known as short-circuiting and it's not an optimization, it's behavior mandated by the standard. If the compiler did anything else, it'd not be a valid implementation.
This allows you to do things like a != NULL && a->isValid()
and be sure that you're not dereferencing a null pointer.
Upvotes: 6