0

I know that bitwise operations must be done only with unsigned integers and static analyzers warn me about this.

What is a good practice to #define bitwise macros flags? I saw these two ways till now:

#define MACRO_FLAG1 (1U << 0U)
#define MACRO_FLAG2 (unsigned int)(1 << 1)
Taw
  • 479
  • 3
  • 15
  • 1
    As StoryTeller says in his answer, the first one is better. But you do not need to force the shift amount to be unsigned, so `(1U << 0)` is perfectly fine. The type of the right-hand argument of the bitwise shift operator does not matter much - it just needs to be an integer type. – Ian Abbott Mar 05 '18 at 15:11
  • Yes, I also thought that `(1U << 0)` is fine but it seems that clang-tidy's hicpp-signed-bitwise will not silence until I put 0U, also. – Taw Mar 05 '18 at 15:22
  • [the second one suffers from UB](https://stackoverflow.com/q/9867883/995714) if the value shifts into the sign bit, the first one simply wraps discard the high bits – phuclv Mar 05 '18 at 16:00

1 Answers1

2

The first macro expresses the shift with unsigned integers, and the result itself is unsigned for it.

The second one uses signed integers for the shift, and then casts the signed result. It's subject to the same weaknesses you mentioned hearing about.

It's worth noting though, that the static analyzers are warning you about possible problems. Depending on your range of flags, you may never encounter said problems, even when you use signed integers.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • Thanks for the reply, I know what each line does, my question was if there is a general good practice about how to define such unsigned flags. I try to have my code warning-free (compiler and static analyzer) :) – Taw Mar 05 '18 at 15:09
  • 1
    @Taw - Good practice as opposed to what? Please see [ask] to avoid misunderstandings with your questions. – StoryTeller - Unslander Monica Mar 05 '18 at 15:10
  • 2
    @Taw I don't think you know. The second definition is wrong. You shift the **signed** integer and your cast hides the problem. I do not know if the bad, wrong code is a good or a bad practice. – 0___________ Mar 05 '18 at 15:15