Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Just learned here that -Wsequence-point comiplation flag will pop a warning when the code can invoke UB. I tried it on a statement like

int x = 1;
int y = x+ ++x;

and it worked very nicely. Until now I have compiled with gcc or g++ only using -ansi -pedantic -Wall . Do you have any other helpful flags to make the code more safe and robust?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
342 views
Welcome To Ask or Share your Answers For Others

1 Answer

As alk summed up, use these flags:

-pedantic -Wall -Wextra -Wconversion


First, I think you don't want to use the -ansi flag, as suggested in Should I use "-ansi" or explicit "-std=..." as compiler flags?

Secondly, -Wextra seems to be quite useful too, as suggested in -Wextra how useful is it really?

Thirdly, -Wconversion seems also useful, as suggested in Can I make GCC warn on passing too-wide types to functions?

Fourthly, -pedantic is also helpul, as suggested in What is the purpose of using -pedantic in GCC/G++ compiler?.

Lastly, enabling -Wall should be fine in this case, so I am pretty doubtful about what you said.

Example with :

Georgioss-MacBook-Pro:~ gsamaras$ cat main.c 
int main(void)
{
    int x = 1;
    int y = x+ ++x;
    return 0;
}
Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
main.c:4:16: warning: unsequenced modification and access to 'x' [-Wunsequenced]
    int y = x+ ++x;
            ~  ^
main.c:4:9: warning: unused variable 'y' [-Wunused-variable]
    int y = x+ ++x;
        ^
2 warnings generated.
Georgioss-MacBook-Pro:~ gsamaras$ gcc -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.38)
Target: x86_64-apple-darwin16.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

Example with , same version:

Georgioss-MacBook-Pro:~ gsamaras$ cp main.c main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall main.cpp 
main.cpp:4:16: warning: unsequenced modification and access to 'x'
      [-Wunsequenced]
    int y = x+ ++x;
            ~  ^
main.cpp:4:9: warning: unused variable 'y' [-Wunused-variable]
    int y = x+ ++x;
        ^
2 warnings generated.

Relevant answer of mine, that Wall saves the day once more with a similar problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...