'Can clang format add braces to single line if statements etc
Is there an option for clang-format to add braces to all if()/do/while statements etc?
eg
if( i == 42 )
std::cout << "You found the meaning of life\n";
else
std::cout << "Wrong!\n";
to
if( i == 42 )
{
std::cout << "You found the meaning of life\n";
}
else
{
std::cout << "Wrong!\n";
}
Using
$ clang-format --version
clang-format version 3.6.0
Solution 1:[1]
Starting clang-format-15 (currently trunk), the answer is yes - using the new InsertBraces option, which landed just today:
https://github.com/llvm/llvm-project/commit/77e60bc42c48e16d646488d43210b1630cd4db49
https://reviews.llvm.org/D120217
From the clang-format documentation:
InsertBraces (Boolean) clang-format 15
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.
Warning:
Setting this option to true could lead to incorrect code formatting due to clang-format’s lack of complete semantic information. As such, extra care should be taken to review code changes made by this option.
false: true:
if (isa<FunctionDecl>(D)) vs. if (isa<FunctionDecl>(D)) {
handleFunctionDecl(D); handleFunctionDecl(D);
else if (isa<VarDecl>(D)) } else if (isa<VarDecl>(D)) {
handleVarDecl(D); handleVarDecl(D);
else } else {
return; return;
}
while (i--) vs. while (i--) {
for (auto *A : D.attrs()) for (auto *A : D.attrs()) {
handleAttr(A); handleAttr(A);
}
}
do vs. do {
--i; --i;
while (i); } while (i);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | valiano |
