Answer a question

It's a bit frustrating that there are a lot of things that vscode does automatically but when using a switch-case statement it doesn't automatically indent after the colon. This is what I get if I were to type without interfering

int x = 32;
switch (x){
    case 33:
    break;
    case 32:
    break;
    default:
}

And this is what I would like the to see

int x = 32;
switch (x){
    case 33:
        break;
    case 32:
        break;
    default:
}

Answers

Clang Format for customizable formatting rules

For any C++ formatting needs I would recommend using Clang Format, which can be seamlessly integrated into VS Code.

In you example you may use the IndentCaseLabels style option:

IndentCaseLabels (bool)

Indent case labels one level from the switch statement.

When false, use the same indentation level as for the switch statement. Switch statement body is always indented one level more than case labels (except the first block following the case label, which itself indents the code - unless IndentCaseBlocks is enabled).

false:                                 true:
switch (fool) {                vs.     switch (fool) {
case 1:                                  case 1:
  bar();                                   bar();
  break;                                   break;
default:                                 default:
  plop();                                  plop();
}                                      }

Applied to your example:

//  IndentCaseLabels: true
int x = 32;
switch (x) {
  case 33:
    void();
    break;
  case 32:
    break;
  default:
}

//  IndentCaseLabels: false
int x = 32;
switch (x) {
case 33:
  void();
  break;
case 32:
  break;
default:
}

Integration of Clang Format into VS Code

Citing Edit C++ in Visual Studio Code from the VS Code documentation [emphasis mine]:

[...]

Code formatting

The C/C++ extension for Visual Studio Code supports source code formatting using clang-format which is included with the extension.

You can format an entire file with Format Document (Ctrl+Shift+I) or just the current selection with Format Selection (Ctrl+K Ctrl+F) in right-click context menu. You can also configure auto-formatting with the following settings:

  • editor.formatOnSave - to format when you save your file.
  • editor.formatOnType - to format as you type (triggered on the ; character).

By default, the clang-format style is set to "file" which means it looks for a .clang-format file inside your workspace. If the .clang-format file is found, formatting is applied according to the settings specified in the file. If no .clang-format file is found in your workspace, formatting is applied based on a default style specified in the C_Cpp.clang_format_fallbackStyle setting instead. Currently, the default formatting style is "Visual Studio" which is an approximation of the default code formatter in Visual Studio.

[...]

Logo

开发云社区提供前沿行业资讯和优质的学习知识,同时提供优质稳定、价格优惠的云主机、数据库、网络、云储存等云服务产品

更多推荐