Search code examples
cclangclang-format

How do I make clang to ignore the indentations during formatting?


I have clang-format properly installed on my device. The Problem is whenever I format in my editor, I always get this:

int main() {

  printf("Hello world!");

  for (int i = 0; i < 5; i++) {
    printf("%d", i);
  }

  return 0;
}

My expected output is this:

int main() {

    printf("Hello world!");

    for (int i = 0; i < 5; i++) {
        printf("%d", i);
    }

    return 0;

}

As you can see, on my expected output, I wanted it to have an indentation (whenever I make curly braces), however on the output I get, the indentation gets reduced to two spaces per level.

I tried searching for solutions on YouTube, however I couldn't find one.


Solution

  • The default indentation in clang-format is likely set to 2 spaces, which is why you are seeing that in your formatted code. If you prefer 4 spaces of indentation, you need to change the IndentWidth setting in your .clang-format file.

    Here is an example configuration that sets the indent width to 4 spaces:

    BasedOnStyle: LLVM
    IndentWidth: 4
    

    This tool comes in handy: https://zed0.co.uk/clang-format-configurator/