C++ begins
Widely Accepted Convention
Maintaining consistent conventions as a habit within a program becomes increasingly essential as the program’s size expands.
Variable and function
CamelCase will be utilized for variable names. In CamelCase, the initial character is in lowercase, with subsequent words capitalized, and no spaces between them. Here’s an example of CamelCase:
1
2
double firstVariable
double secondVariable
Additionally, camel case is adopted for function names. Function names typically take the form of “verb + noun”.
1
2
3
double calculateTotalPrice(int quantity, double unitPrice) {
return quantity * unitPrice;
}
There is one exception for constant variables: all letters are capitalized.
1
double PI = 3.141592
Class and struct
For classes and structs, Pascal case is typically utilized, also known as upper camel case. Inside the class and struct, variables and functions still follow camel case, as prescribed. Additionally, underscores “_” can be placed at the end of protected or private class variables.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Student {
public:
Student(const std::string& name, const int number):
name_(name),
number_(number)
{
}
std::string getName() const {
return name_;
}
int getNumber() const {
return number_;
}
private:
std::string name_;
int number_;
};
Remarks
For programming languages that require compilation, running small code fragments can be a tedious process. To quickly check small modules of code, I recommend using web-based environments such as https://www.mycompiler.io. These platforms offer convenience and efficiency for testing code without the need for local compilation setups.
Comments powered by Disqus.