Skip to the task
Layout
Back to classic view
READTask 1 of 23 · step 1: Code styleCode style
Code style in practice/02/

.clang-format and Reformat Code (Ctrl+Alt+L), what the formatter doesn't do, and why the course has zero warnings.

Details & hint

Code is read far more often than it is written: by you a week later, by the lecturer, by a teammate. When the whole course writes in one style, you read code faster and see bugs sooner.

.clang-format and Reformat Code

The repository root has a file called .clang-format: the course's style rules.

BasedOnStyle: LLVM
IndentWidth: 4
ColumnLimit: 100
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false

The indent is 4 spaces, a line is at most 100 characters, and ifs and loops are never squeezed onto one line. CLion finds this file by itself, and the status bar at the bottom shows ClangFormat.

To format a file by these rules: Code → Reformat Code, or Ctrl+Alt+L. If you selected part of the code, only that part is formatted. You can also turn on formatting every time you save: Settings → Tools → Actions on Save → Reformat code.

What the formatter doesn't do

Reformat Code takes care of spaces, indents and line breaks. Everything else is your job:

  • Names. average, not v. Variable names are written in lower case with _: birth_year. A loop counter can be i or j.

  • Braces { } on every if, else, for and while, even with one statement inside (topic 3).

  • Comments explain why, not what. The code already says what it does. This comment says nothing:

    count++; /* increase count */
    

    And this one explains what the code can't show:

    int lowest = 10; /* the largest possible: the first grade replaces it */
    
  • Magic numbers. if (grade >= 5): what is that 5? const int pass_mark = 5; and if (grade >= pass_mark) say it themselves.

Zero warnings

-Werror already turns warnings into errors, so a program with a warning doesn't even build. On top of that, CLion underlines suspicious places in yellow that the compiler doesn't count as errors: an unused #include, a variable whose value is never used. Hover over the underline and read it. You find all of a file's findings in the Problems window (Alt+6). The goal is simple: none.

GitHub CI builds with a newer GCC than CLion's, so it may show a warning (an error, with -Werror) that CLion didn't; you must fix it too.

practice 02 CMakeLists.txt Code Diff
UNCHANGED This step does not change this file.
add_executable(p02_card main.c)
target_link_libraries(p02_card PRIVATE course_input)