Is there a GCC warning to catch if statement and operation on same line

Viewed 75

Is there a GCC warning I can turn on that can catch it if I have an if-statement followed by an operation on the same line, like in this example

    if ( ReadOnly == accessMode ) readFile();

I want to use this to enforce a coding standard.

3 Answers

I don't think there is a gcc warning, since that line is perfectly legal in either C or C++. In Linux, you can use the grep command to find these lines in your .cpp files.

grep -n -e "^\s\+if(.*;$" -e "^\s\+if\s\+(.*;$" *.cpp

Or simply

grep -n "^\s\+if\s\{0,3\}(.*;$" *.cpp

The $ in the above line means end-of-line, can be removed to match more results.

^ matches start-of-line. \s\+ matches one or more spaces. \s\{0,3\} match 0 to 3 spaces. .* matches everything.

The above grep commands don't find break lines, such as

if( readOnly == access )
        readFile();

If the objective is to enforce a coding "standard", like some kind of coding style, I would suggest to use a tool for that purpose.

The compiler, although being able to emit diagnostics for some "code smells", they are usually related to code behavior, possible UB or other misuses of the language, not so related to coding style. For instance, it can emit a diagnostics for the following "style" misuse:

if (x)
  doSomething();
  doSomethingElse();  //Diagnostic: this line is not protected by the if.

But these diagnostics are limited to very few very obviously wrong code.

Regexes, while probably solving your current issue, will fall short for a general style enforcement.

So, I think the ideal way would be to use a tool designed for enforcing coding style. There are plenty of such tools. I would suggest either:

  • clang-format: widely used and supported.
  • uncrustify: tons of options to define your own style.

In most editors you can enable them to be run "on saving", restyling your code to fit your style.

Related