Visual Studio Code formatting for "{ }"

  • Go File -> Preferences -> Settings
  • Search for C_Cpp.clang_format_fallbackStyle
  • Change from "Visual Studio" to "LLVM", "Google" or "WebKit"

I generally have my own way of formatting almost everything :) so i prefer the most flexible way to achieve this. VS code is by far the most flexible editor as far as c++ formatting is concerned and also "easy".

This is what you should do to get custom formatting.

  • create a file named .clang-format under the top folder of your work space.
  • then start putting your configuration. you can refer page Clang format Style to know various options available.
  • save the file and then either use Format Document (Ctrl+Shift+I) or Format Selection (Ctrl+K Ctrl+F)

Here is my file for your reference.

Standard: Cpp11
BasedOnStyle: LLVM
IndentWidth: 4
ColumnLimit: 0
AccessModifierOffset: -4
NamespaceIndentation: All
BreakBeforeBraces: Custom
BraceWrapping:
  AfterEnum: true
  AfterStruct: true
  AfterClass: true
  SplitEmptyFunction: true
  AfterControlStatement: false
  AfterNamespace: false
  AfterFunction: true
  AfterUnion: true
  AfterExternBlock: false
  BeforeCatch: false
  BeforeElse: false
  SplitEmptyRecord: true
  SplitEmptyNamespace: true

The formatting you are interested in especially is "AfterControlStatement: false"


base on @Chris Drew's answer

  1. Go Preferences -> Settings
  2. Search for C_Cpp.clang_format_fallbackStyle
  3. Click Edit, Copy to Settings
  4. Change from "Visual Studio" to "{ BasedOnStyle: Google, IndentWidth: 4 }"

e.g.

  • "C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: Google, IndentWidth: 4, ColumnLimit: 0}"
  • btw ColumnLimit: 0 is helpful too, because google limit will break your code to next line when you do not need it.

If you want more:

  • check https://clang.llvm.org/docs/ClangFormatStyleOptions.html
  • customize your functionality to "C_Cpp.clang_format_fallbackStyle" for your loved favor.

More detail:

English: https://medium.com/@zamhuang/vscode-how-to-customize-c-s-coding-style-in-vscode-ad16d87e93bf

Taiwan: https://medium.com/@zamhuang/vscode-%E5%A6%82%E4%BD%95%E5%9C%A8-vscode-%E4%B8%8A%E8%87%AA%E5%AE%9A%E7%BE%A9-c-%E7%9A%84-coding-style-c8eb199c57ce