Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent clang-format from adding a single semicolon to a new line?

I have this line of code in C++

while (fread(pixel_array++, sizeof(byte), 3, fp));

but when I use clang-format, it splits the semicolon and add it into a new line

while (fread(pixel_array++, sizeof(byte), 3, fp))
    ;

I don't like this kind of style, and I just prefer to keep the original one.

How should I modify my clang-format configuration? Thanks.

like image 234
KaitoHH Avatar asked Apr 04 '17 04:04

KaitoHH


People also ask

How do you customize your 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.

Can clang-format break code?

Short answer: YES. The clang-format tool has a -sort-includes option. Changing the order of #include directives can definitely change the behavior of existing code, and may break existing code.

What is clang-format default style?

clang-format file uses YAML format: key1: value1 key2: value2 # A comment. ... The configuration file can consist of several sections each having different Language: parameter denoting the programming language this section of the configuration is targeted at.

Is clang-format good?

clang-format is a tool to automatically format C/C++/Objective-C code, so that developers don't need to worry about style issues during code reviews. It is highly recommended to format your changed C++ code before opening pull requests, which will save you and the reviewers' time.


2 Answers

clang-format 5.0 currently doesn't recognize that type of loop. Unfortunately as of clang-format version 5, you won't get a setting that does what you need.

Looking up the Clang Format Style Options, the closest that I've found is AllowShortLoopsOnASingleLine: true, but that setting doesn't recognize the loop condition as being the body of the loop.

As long as clang-format doesn't recognize those kinds of loops, what I'd do is to mark it your code with // clang-format off and then // clang-format on around your block of code.

like image 152
Unglued Avatar answered Sep 18 '22 11:09

Unglued


Apparently this is not possible, but a workaround could be to replace the semicolon with an empty block. If both AllowShortLoopsOnASingleLine and AllowShortBlocksOnASingleLine are set, than it will be formatted as

while (fread(pixel_array++, sizeof(byte), 3, fp)) {}
like image 24
dpi Avatar answered Sep 18 '22 11:09

dpi