Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference in compiler behavior for each of these snippets?

Tags:

c++

comparison

Please consider following code:

1.

uint16 a = 0x0001;

if(a < 0x0002)
{
    // do something
}

2.

uint16 a = 0x0001;

if(a < uint16(0x0002))
{
    // do something
}

3.

uint16 a = 0x0001;

if(a < static_cast<uint16>(0x0002))
{
    // do something
}

4.

uint16 a = 0x0001;
uint16 b = 0x0002;

if(a < b)
{
    // do something
}

What compiler does in backgorund and what is the best (and correct) way to do above testing?

p.s. sorry, but I couldn't find the better title :)

EDIT:

values 0x0001 and 0x0002 are only example. There coudl be any 2 byte value instead.

Thank you in advance!

like image 855
HotHead Avatar asked Feb 03 '26 18:02

HotHead


2 Answers

The last example is the best code-wise, as you shouldn't use "magic constants" in your code.

In fact, the best way would be to make b const, (edit) and use meaningful names:

uint16 currentSpeed = 0x0001; 
const uint16 cMaxSpeed = 0x0002; 

if (currentSpeed < cMaxSpeed) 
{ 
    // do something 
} 

Other than that, there is very little difference "under the bonnet" between your examples.

like image 92
Jason Williams Avatar answered Feb 06 '26 06:02

Jason Williams


It is usually best to avoid unnamed "magic" numbers in code, since it is hard for a maintainer to understand what the number is supposed to mean. For this reason, it is good practice to name your constants. For this reason, don't do number 1.

In C++, it is best to use static_cast, rather than C style casts. I'm sure there are probably other questions about why this is the case, but the best reference here is Meyers (Effective C++). For this reason, prefer 3 over 2, but 3 still suffers from the magic number problem.

Four is the best, except the variable names are meaningless, and it might make sense for one or both variables to be const.

I'm not sure if there is any difference between any in terms of compiled code, but there might be due to the literal being interpreted as something other than uint16. It might be a uint32 for instance, although you should still get the expected result.

like image 45
mch Avatar answered Feb 06 '26 07:02

mch