Reputation: 1029
Say, I have a function like shown below
void caller()
{
int flag = _getFlagFromConfig();
//this is a flag, which according to the implementation
//is supposed to have only two values, 0 and 1 (as of now)
callee_1(flag);
callee_2(1 == flag);
}
void callee_1(int flag)
{
if (1 == flag)
{
//do operation X
}
}
void callee_2(bool flag)
{
if (flag)
{
//do operation X
}
}
Which of the callee functions will be a better implementation?
I have gone through this link and I'm pretty convinced that there is not much of a performance impact by taking bool for comparison in an if-condition. But in my case, I have the flag as an integer. In this case, is it worth going for the second callee?
Upvotes: 1
Views: 3126
Reputation: 37208
One case where the difference between bool and int results in different (optimized) asm is the negation operator ("!").
For "!b", If b is a bool, the compiler can assume that the integer value is either 1 or 0, and the negation can thus be a simple "b XOR 1". OTOH, if b is an integer, the compiler, barring data-flow analysis, must assume that the variable may contain any integer value, and thus to implement the negation it must generate code such as
(b != 0) ? 0: 1
That being said, code where negation is a performance-critical operation is quite rare, I'm sure.
Upvotes: 0
Reputation: 25799
It won't make any difference in terms of performance, however in terms of readability if there are only 2 values then a bool
makes more sense. Especially if you name your flag something sensible like isFlagSet
.
Upvotes: 8
Reputation: 258608
In terms of efficiency, they should be the same.
Note however that they don't do the same thing - you can pass something other than 1
to the first function, and the condition will evaluate to false even if the parameter is not itself false. The extra comparison could account for some overhead, probably not.
So let's assume the following case:
void callee_1(int flag)
{
if (flag)
{
//do operation X
}
}
void callee_2(bool flag)
{
if (flag)
{
//do operation X
}
}
In this case, technically the first variant would be faster, since bool
values aren't checked directly for true
or false
, but promoted to a word-sized type and then checked for 0
. Although the assembly generated might be the same, the processor theoretically does more work on the bool
option.
Upvotes: 2
Reputation: 153919
If the value or argument is being used as a boolean, declare it bool
.
The probability of it making any difference in performance is almost 0,
and the use of bool
documents your intent, both to the reader and to
the compiler.
Also, if you have an int
which is being used as a flag (due to an
existing interface): either use the implicit conversion (if the
interface documents it as a boolean), or compare it with 0
(not with
1
). This is conform with the older definitions of how int
served as
a boolean (before the days when C++ had bool
).
Upvotes: 1