C/C++ code specification

C/C++ code specification

The code format is not necessary in some languages. For example, in C language, you can add any number between statements ;, and you can add a lot of spaces; you can write a statement in two lines, or you can put all the codes on one line. Some languages ​​are very sensitive to the code format, such as Python, the same level of indentation must be the same between the statements at the same level.

The code specification is a further requirement on the code format, in order to make the code easier to read and make errors easier to check.

In order to keep the code clean and beautiful, the code style needs to be unified , that is, the code style of the same piece of code and the same project needs to be consistent. A person's style may be fixed, but the style of a project usually needs to be formulated in advance.

Different people may have different coding styles, but there are also some norms that everyone abides by. You can read more well-written and standardized codes to get familiar with some basic specifications that everyone abides by.

The following will introduce what should be paid attention to in the code specification of C language.

indentation

Indentation is a very common thing, it is used to show the level of code. Generally, you can use Tabor spaces to form indentation.

To enter one Tab, just press the Tab key on the keyboard.

To use Tabfor indentation, only one is Tabenough; while for space for indentation, 2 or 4 spaces are generally used as an indentation.

According to different editor settings or personal habits, one Tabmay be displayed as 2/4/8 spaces and so on. Therefore, do not mix Tab with spaces (Space) and indentation (Tab) . This may cause the level of code display to become confusing and difficult to read.

int foo(int num) {
    
    
    // 一级缩进
    if (num % 2 == 0) {
    
    
        // 二级缩进
        return num + 1;
    }
    else return num;
}

big parantheses

There are generally two ways, one is to { put the opening brace " " at the end of the line, and the other is { to occupy a line alone. Generally, the first type is more common. There will even be colleagues who put elsekeywords in ifcurly braces in the statement.

int foo(int num) {
    
    
    if (num % 2 == 0) {
    
    
        return num + 1;
    } 
    else return num;
}

The wording of brace wrap:

int foo(int num)
{
    
    
    if (num % 2 == 0)
    {
    
    
        num *= 2;
        num += 1;
    } 
    return num;
}

Of course, the format is not absolute, it can be adjusted flexibly according to the situation, as long as it is easy to read . For example, if several sentences are relatively simple and logically related, they can also be placed on one line.

<template class T>
std::vector<T> stack_reverse(std::stack<T> _stack) {
    
    
    std::vector<T> result;
    while (!_stack.empty()) {
    
     result.pusk_back(_stack.top()); _stack.pop(); }
    return result;
}

Space

For example if, else, for, whileand so after leaving the space key , you can highlight keywords. Correspondingly, the parentheses after the function name should follow immediately .

void print_vector_int(const std::vector<int> & a) {
    
    
    for (auto i : a) std::cout << i << ' ';
    std::cout << std::endl;
}

Left and right parentheses (, )usually tightly wrapped contents, and ,, ;then closely followed by the character of its left side, the right side to leave a blank space.

std::vector<int> a = {
    
    1, 2, 3, 4, 5};

Binary operator (e.g. +, -, =, ==, +=, <, %etc.) have left and right spaces.

int num1 = 10 / 2;
int num2 = 20 % 3;
int val = num1 + num2;

Unary operators (e.g. !, ++, --, *, &etc.) immediately after its operands, no spaces before and after.

std::vector<int> a = {
    
    
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
};
auto i = a.begin();
while (i != a.end()) {
    
    
    std::cout << *i << ' ';
    ++i;
}

Square brackets [], member operators ., ->and their operands are also immediately followed, that is , there are no spaces before and after them.

std::vector<int> a = {
    
    1, 2, 3, 4, 5};
a[0] = a[1] + a[2];
a.erase(a.begin());

int val = 10;
auto b = new std::vector<int>();
b->push_back(val);
b->erase(b->begin());

Symbolic naming

Develop good and standardized variable/function naming methods and habits.

Reference reading:

The naming of symbols mainly includes underscore method, camel case method, etc., such as find_first_of(), namedWindow()etc.

Macro names and enumeration name (in fact, the enumeration can be viewed as a macro definition) generally use all uppercase + underscore, such as BGR2GRAY, MAX_LENGTH, BLUEand so on.

Generally speaking, functions, local variable names, global variable names, macro names, etc., can be distinguished from each other by using different nomenclature .

Variable name should also have some significance , for example tmp, tempgenerally designated temporary variables i, j, kand the like generally used as iteration, cnttypically for counting.

struct MyStruct {
    
    
    int val_a;
    int val_b;
    char class_type;
    enum Type {
    
    TYPE_A, TYPE_B};
    
    bool isValid() {
    
     return val_a > 10 && val_b > 20; }
}

Comment

Remember to add some comments when writing code. Good comments can make it easier for yourself and others to read and modify the code.

Nothing is necessary, just give hints in the key parts.

Generally, for a function, it should be clearly stated its functions and the meaning of each parameter of the function; for variables, there should be an introduction to its function. Comments of this nature are generally written near the declaration of a function or variable . For the definition part of the function, it is better to have a corresponding explanation, which can tell the reader what a certain line or a certain piece of code achieves, or why it is written in this way.

Many editors and IDEs can recognize these comments and display the prototype and comments of the function when the mouse hovers over their call, which is very convenient.

The function and variable name itself should also reflect a certain meaning. If appropriate, the code you have self-explanatory (self-explaining), and unnecessary additional write a comment.

It is not recommended to use Chinese pinyin to name symbols, let alone use Chinese abbreviations. Because of the Chinese language, there are many homophones, and there are more words with the same pinyin first letter. It is difficult for others to think of the specific words. Since it is programmed with 26 English letters, it is also recommended to name the variables in English.

To a certain extent, the name of a variable also requires a certain degree of proficiency in English. For example, although some words have similar meanings, one of them will be more appropriate than others.

The following is the reference code for "choose the monkey king" (that is, the "Joseph question"):

// return the postion number of the monkey king
int get_monkey_king(int n, int m) {
    
    
    std::queue<int> monkeys_queue;
    for (int i = 1; i <= n; ++i) monkeys_queue.push(i);
    cnt = 0;
    while (monkeys_queue.size() > 1) {
    
    
        ++cnt;
        auto monkey = monkeys_queue.front();
        monkeys_queue.pop();
        if (cnt == m) cnt = 0; 
        else monkeys_queue.push(monkey);
    }
    std::cout << monkeys_queue.front() << std::endl;
}

int main() {
    
    
    std::cin >> n >> m;
    std::cout << get_monkey_king(n, m);
}

Guess you like

Origin blog.csdn.net/henry_23/article/details/112976333