C++ is an extension of the C programming language. It has various applications such as system programming, embedded programming, game development, and software development. It allows programmers to write code optimized for speed and low-level memory access.
In C++, user-defined names for variables, functions, classes, objects, etc are known as identifiers. An identifier can include letters, numbers, and underscores, however; it must start with a letter (either uppercase or lowercase) or an underscore.
Let's see some identifiers that are using underscore in the following code:
#include <iostream>using namespace std;int main() {int _var1 = 5;int var2_ = 6;int var_3 = 7;cout<<"Variable starting with an underscore = " << _var1 << endl;cout<<"Variable ending with an underscore = " << var2_ << endl;cout<<"Variable with an underscore in the middle = " << var_3 << endl;return 0;}
In the above code, we define some variables that start with an underscore, end with an underscore, and have an underscore in the middle.
We can use underscores in our identifiers any way we’d like, however, below are some of the rules we must keep in mind while using an underscore in an identifier to follow the general naming conventions in C++:
We should avoid starting identifier names with an underscore as it is usually reserved for operating system features and system level names. Various C++ libraries and compilers use identifiers that begin with an underscore so there is a chance that we might run into a conflict.
We should avoid ending identifier names with an underscore. Even though this convention is not reserved by libraries and compilers, underscores at the end of an identifier are not recommended to keep the visual appeal of our code consistent and to make it easier to understand.
We should avoid starting identifier names with two consecutive underscores. For example __foo
is also reserved.
Other than the few rules mentioned above, we can use underscores in identifiers without much hassle. Generally, it is encouraged to use underscores between words of an identifier to separate them. This is known as the “Snake case” for example, my_identifier
.
Free Resources