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.
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.
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:
In most editors you can enable them to be run "on saving", restyling your code to fit your style.
As LoPiTaL suggests, use a tool designed to enforce coding standards. The compiler is ill-suited for this purpose.
For your specific ask, clang-format has the option AllowShortIfStatementsOnASingleLine that you can use.