4

Had a bug in this code:

bool x;
    
for(const auto a : b)
{
    x = x && a.b;
}

x should have initialized to true.

I'd like to raise a compiler error that the bool wasn't explicitly initialized, but I cannot find a warning which covers this. We have the obvious flags:

-Wall \
-pedantic \
-Werror=uninitialized \ 

Is there another Clang warning that would catch this and other uninitialized variables?

0

2 Answers 2

11

For this particular issue, compile with -Werror=conditional-uninitialized and you'll get a clear warning, turned into an error:

<source>:10:13: error: variable 'x' may be uninitialized when used here [-Werror,-Wconditional-uninitialized]
   10 |         x = x && a.b;
      |             ^
<source>:7:11: note: initialize the variable 'x' to silence this warning
    7 |     bool x;
      |           ^
      |            = false
Sign up to request clarification or add additional context in comments.

4 Comments

Perfect. Thank you. Are there any others which you would advise being enabled?!
@intrigued_66 You're welcome! When I use clang, I do it the other way around. I use -Weverything and then selectively turn off the warnings I don't want (like incompatibility with C++98 etc.). For example: -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-newline-eof -Wno-c++20-compat -Wno-missing-prototypes -Wno-ctad-maybe-unsupported
I like -Wall -Wextra -Wpedantic -Werror. There's probably a handful of stuff from -Weverything that might be useful but most of it is compatibility warnings that can often be mutually exclusive with these categories.
@PatrickRoberts I find there are many useful warnings one could enable ... but, I mainly use CodeChecker for static analysis. It's LLVM-based so my personal "light"-filter is -Weverything.
2

-fsanitize=bool can catch it if you enable optimizations.

#include <vector>

struct foo { bool b = true; };

int main() {
    bool x;
    std::vector<foo> b(5);

    for(const auto a : b)
    {
        x = x && a.b;
    }
}

clang(trunk) and -fsanitize=bool -O3:

UndefinedBehaviorSanitizer:DEADLYSIGNAL
==1==ERROR: UndefinedBehaviorSanitizer: SEGV on unknown address 0x000000000001 (pc 0x000000000001 bp 0x000000000000 sp 0x7ffe5711f3a8 T1)
==1==Hint: pc points to the zero page.
==1==The signal is caused by a READ memory access.
==1==Hint: address points to the zero page.
UndefinedBehaviorSanitizer:DEADLYSIGNAL
UndefinedBehaviorSanitizer: nested bug in the same thread, aborting.

1 Comment

That's at runtime though, I think what's being requested is compile-time diagnosis

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.