Indent braces with clang-format - indentation

I'd like to use clang-format to indent braces like so,
for(...)
{
[...]
[...]
}
Clang-format can do this with BreakBeforeBraces: Whitesmiths, but I would like to customise that. The manual seems to suggest that IndentBraces does the trick, but that produces
for(...)
{
[...]
[...]
}
and other weird things. Am I using this wrong or is this a bug? (tested with clang-format-13).

Related

How to indent lambdas in complex assignment expressions by 4 spaces

I have an assignment expression like this (formatted by clang-format):
auto typeParams = node->typeParams | std::views::transform([&](auto p) {
return m_irCtx.make(IRGenericType(p));
});
I would like to have it formatted like this:
auto typeParams = node->typeParams | std::views::transform([&](auto p) {
return m_irCtx.make(IRGenericType(p));
});
Which .clang-format option controls how lambdas are indented relative to the parent scope? How can I achieve this?
EDIT: Setting LambdaBodyIndentation to OuterScope does not change anything
In this specific case (and if it's the only case or only one of a few) I'd just format by hand:
// clang-format off
auto typeParams = node->typeParams | std::views::transform([&](auto p) {
return m_irCtx.make(IRGenericType(p));
});
// clang-format on
Yes, that's cheating. Clang-format works reasonably well if you're happy with what it does but you cannot configure it to do anything. In these cases, you're welcome to switch the automation off and do it manually.
Looking at the code in question, I'd say that the closing brace and parenthesis should be indented by at least one level. However, what do I know. If you want it like this, write it like this and don't let clang-format touch it.

Expanding do while condition in C++

im a beginner starting to learn c++ i have a question.. Can i write scripts in do while loop i mean like this...
//you type do then like
do{
// your code here
}while(condition{ // <-- the question is here
then the code of the script
} ) closing Parenthesis and curly braces
yeah if you didn't understand that my question was that can i expand my condition in the while Parenthesis?? please answer because I'm learning C++ and I wanna improve.
The while condition takes an expression. That includes things like variables (foo), operators (1 + 2), and function calls. But it excludes things like if statements and additional loops. If you need to do something complicated inside of a while block, you should put it in a function.
do {
// ...
} while (should_continue(foo, bar));
bool should_continue(int foo, int bar) {
// ... complicated code goes here ...
}
Technically speaking, in C++11 and onward, you can create and evaluate a lambda in the same line, allowing arbitrary statements in expression context, but this is not very readable and should generally be a sign that your code needs to be split up into more functions.
// Don't do this; your coworkers will despise you.
do {
// ...
} while (([&]() {
// ... complicated code goes here ...
})());
Some non-portable compiler extensions will also allow the syntax you suggested in the question, where you can just throw braces { ... } with arbitrary statements in expression context. But, again, this is non-portable and not very readable code to begin with. So just write a function.

clang-format: indentation of macros

I am trying to apply clang-format to an existing code base and came across the following issue:
Simplified (and formatted) sample code:
#define QUERY_BEGIN()
#define QUERY_NORESULT()
#define QUERY_END()
void foo()
{
int a = 0;
QUERY_BEGIN()
a = 1;
QUERY_NORESULT()
a = 2;
QUERY_END()
}
I set the following options:
MacroBlockEnd: 'QUERY_END'
MacroBlockBegin: 'QUERY_BEGIN'
What I want to achieve is the following formatting of the macro part:
QUERY_BEGIN()
a = 1;
QUERY_NORESULT()
a = 2;
QUERY_END()
My first guess was to set QUERY_NORESULT as MacroBlockEnd and MacroBlockBegin but that didn't help. It results in the following formatting:
QUERY_BEGIN()
a = 1;
QUERY_NORESULT
a = 2;
QUERY_END()
Is there currently a way to achieve the indentation as shown above?
Bad news: Sorry, this is not available in the current release version of clang-format(7).
Good news: There is a StatementMacros option, which is available since clang-format 8(not release yet, but you can build from source).
See this commit:
Summary:
Some macros are used in the body of function, and actually contain the trailing semicolon: they should thus be automatically followed by a new line, and not get merged with the next line. This is for example the case with Qt's Q_UNUSED macro:
void foo(int a, int b) {
Q_UNUSED(a)
return b;
}
This patch deals with these cases by introducing a new option to specify list of statement macros. This re-uses the system already in place for foreach macros, to ensure there is no impact on performance.
Document:
◆ StatementMacros
std::vector clang::format::FormatStyle::StatementMacros
A vector of macros that should be interpreted as complete statements.
Typical macros are expressions, and require a semi-colon to be added; sometimes this is not the case, and this allows to make clang-format aware of such cases.
For example: Q_UNUSED
Definition at line 1061 of file Format.h.
Referenced by clang::format::FormatTokenLexer::FormatTokenLexer(), clang::format::getLLVMStyle(), llvm::yaml::MappingTraits< FormatStyle >::mapping(), and operator==().
Solution:
build clang from source/wait for llvm/clang8 release, then
put StatementMacros ['QUERY_BEGIN()', 'QUERY_NORESULT()', 'QUERY_END()'] into your .clang-format.
Workaround for old clang-format
// clang-format off
void unformatted_code ;
// clang-format on
Turn off clang-format in this macro statements.
clang-format 3.7 added support for this under the names MacroBlockBegin and MacroBlockEnd. These config options are weirder than the newer-style (Attribute|Statement|If|Foreach)Macros options (which take lists); the older-style MacroBlock(Begin|End) options take regular expressions, which means that if you have multiple begin/end macros, you must glue them together like this:
MacroBlockBegin: '(FIRST_MACRO|SECOND_MACRO)'
Anyway, for your exact input, and this .clang-format file:
$ cat .clang-format
---
Language: Cpp
BasedOnStyle: LLVM
MacroBlockBegin: 'QUERY_BEGIN'
MacroBlockEnd: 'QUERY_END'
...
clang-format 14.0.6 produces this formatted output:
#define QUERY_BEGIN()
#define QUERY_NORESULT()
#define QUERY_END()
void foo() {
int a = 0;
QUERY_BEGIN()
a = 1;
QUERY_NORESULT()
a = 2;
QUERY_END()
}

Is it wrong to put semicolon after braces of if block?

I use MSVC++ 2008 and 2010 and i am a little confused about auto formatting. When i write code like this :
if(true)
if(true)
{
}
if(true)
{
}
and then i push CTRL+F but nothing happens and last condition stays in place but it should be aligned on a level with first condition. Behavior changes to right way if i add semicolon after braces of second condition like that :
if(true)
if(true)
{
};
if(true)
{
}
So the question is, is it right to add semicolon after condition according to C++ standard or it's just incorrect behavior of MSVC++?
That semicolon is completely superfluous. Looks like you've found a bug in Visual Studio.

do while(false) pattern [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
Why is the do while(false) necessary in the macros below?
#define LOG(message, ...) \
do { \
Lock<MutualExclusion> lock (logMutex); \
.... a lot of code ...
} while (false)
I dont think it serves any functional purpose. Am I overlooking something?
It turns a block into a single statement. If you just use a block (i.e. code enclosed in {}) strange things can happen, for example
#define STUFF() \
{ do_something(); do_something_else(); }
if (cond)
STUFF();
else
//...
the extra semi-colon breaks the syntax. The do {} while(false) instead is a single statement.
You can find more about this and other macro tricks here.
So you are forced to add semicolon at the end of the macro, when you use it. This is a common idiom and only way to enforce it.
If somebody has code that does this:
if (something)
LOG("My log message");
That would expand to:
if (something)
Lock<MutualExclusion> lock (logMutex);
// A bunch of other code
Which is incorrect (only the first line would be under the if statement).
The macro makes sure that the macro call is inside of a block of code.
People use it because otherwise, you can screw up your ifs with compound statements. Imagine
#define hai int x; \
x = 0;
if (condition)
hai;
else
func();
Imagine what the preprocessed source looks like.
if (condition)
int x;
x = 0;
else
func();
Oh wait- now our else doesn't work.
Macros like that however are typically unnecessary in C++.
The reason for this weird practice in #define's is to encapsulate the different assignments within a loop that is executed exactly once, so one may use the macro like a function. For example, with the code you posted, one can write:
if(...)
LOG(x, y);
else
// Something else
and it is expanded as
if(...)
do {...} while(false);
else
// Something else
This would not work without the do...while(false) surrounding the different assignments, because that would be expanded as
if(...)
Lock<MutualExclusion> lock (logMutex);
// Other code... Outside the if statement!
Also forcing a semicolon after the macro makes it look like a function and you wont get errors because you added an semicolon like after a normal function.
It provides local scope to that which is inside the macro.
It looks to me like it is only used for scoping rules, so that Lock<MutualExclusion> falls out of scope at the end of the block.
If that's the reason for it, then it's completely unnecesarry:
// some other code...
string s = "oh hai";
{
Lock<MutualExclusion> lock(logMutex);
// MAGIC HAPPENS
}
s = "oh bai";