Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can clang-format force bracing on all control statement bodies?

IE, this:

if (x > 5)
  return test;

Would always become:

if (x > 5)
{
  return test;
}

I'm not talking about the brace style (Allman, GNU, Whiteman, etc) I just mean having the braces there at all.

There is something to prevent/enable single-line control statements like:

if (x > 5) return test;

which is AllowShortBlocksOnASingleLine, but that's not what I'm looking for here.

If it works on clang 7 that's ideal, but if not let me know.

like image 496
Tyler Shellberg Avatar asked Nov 22 '19 17:11

Tyler Shellberg


People also ask

Where does clang-format look for clang-format?

Standalone Tool. clang-format is located in clang/tools/clang-format and can be used to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.

How do you use clang-format?

You can install clang-format and git-clang-format via npm install -g clang-format . To automatically format a file according to Electron C++ code style, run clang-format -i path/to/electron/file.cc . It should work on macOS/Linux/Windows.

Where do I put the clang file?

clang-format file, we need to place it in the project folder or in any parent folder of the file you want to format. clang-format.exe searches for the config file automatically starting with the folder where the file you want to format is located, all the way to the topmost directory.

How do you change clang-format?

clang-format supports two ways to provide custom style options: directly specify style configuration in the -style= command line option or use -style=file and put style configuration in the . clang-format or _clang-format file in the project directory.


2 Answers

I agree with dovedevic that clang-format can't do this currently. Another alternative to consider is clang-tidy. You can force braces around control statements using this:

clang-tidy -checks='-*,readability-braces-around-statements' -fix-errors myfile.cpp

Explanation:

  • The -* suppresses all checks
  • Then readability-braces-around-statements enables that one check
  • Then -fix-errors tells clang-tidy to fix any issues it finds, even if compilation errors were found

See the documentation for more information.

like image 198
Eric Backus Avatar answered Oct 19 '22 21:10

Eric Backus


The upcoming clang 15 provides the option InsertBraces, which should do exactly what you ask for.

Description:

Insert braces after control statements (if, else, for, do, and while) in C++ unless the control statements are inside macro definitions or the braces  would enclose preprocessor directives.

(https://clang.llvm.org/docs/ClangFormatStyleOptions.html)

like image 2
Bouncner Avatar answered Oct 19 '22 21:10

Bouncner