Any difference in compiler behavior for each of these snippets?

Pay attention to the 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 does the compiler do in backgorund and what is the best (and correct) way to do higher testing?

ps sorry, but I could not find a better name :)

EDIT:

the values ​​0x0001 and 0x0002 are just an example. There coudl can be any value of 2 bytes.

Thank you in advance!

+4
source share
4 answers

The final example is the best code, because you should not use "magic constants" in your code.

Actually, 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 } 

In addition, there are very few “under the hood” differences between your examples.

+7
source

It is usually best to avoid unnamed "magic" numbers in the code, as it is difficult for the developer to understand what that number means. For this reason, it is good practice to name your constants. For this reason, do not do number 1.

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

Four is best, except that variable names are meaningless, and const can make sense for one or both variables.

I am not sure if there is any difference between any words of the compiled code, but maybe because the literal is interpreted as something other than uint16. For example, it could be uint32, although you should still get the expected result.

+3
source

If that's all, there is no difference (GCC, -O2). In all cases, //do something is done simply unconditionally.

So this is just a style issue.

+2
source

Since the numbers you work with are both single and less than 10, there is no difference between decimal and hexadecimal. If you did not define uint16 unexpected way, the cast and / or static_cast should not make any difference. There should be no real difference between directly using a constant and initializing a variable and then using it.

What you need to take care to make sure that the reader can understand what is happening is to give meaningful names, so it’s obvious why you are comparing these elements. Since throws do not actually do anything, you would be better off without them.

+1
source

Source: https://habr.com/ru/post/1306498/


All Articles