Identifiers, Variables, and Constants
Identifiers, variables, and constants are the building blocks of any programming language. They are used to store data and perform operations on them. In this section, we will discuss what they are and how they are used in C++.
Identifiers
Identifiers are names given to different parts of a program such as variables, functions, classes, etc. They are used to identify and refer to these parts in the program. Identifiers in C++ have the following rules:
- They can contain letters, digits, and underscores.
- They must start with a letter or an underscore.
- They are case-sensitive. So
name,Name, andNAMEare different identifiers. - They cannot be a keyword or a reserved word.
Reserved Words in C++
Here are some of the reserved words in C++:
alignasalignofandand_eqasmautobitandbitorboolbreakcasecatchcharchar16_tchar32_tclasscomplconstconstexprconst_castcontinuedecltypedefaultdeletedodoubledynamic_castelseenumexplicitexportexternfalsefloatforfriendgotoifinlineintlongmutablenamespacenewnoexceptnotnot_eqnullptroperatororor_eqprivateprotectedpublicregisterreinterpret_castreturnshortsignedsizeofstaticstatic_assertstatic_caststructswitchtemplatethisthread_localthrowtruetrytypedeftypeidtypenameunionunsignedusingvirtualvoidvolatilewchar_twhilexorxor_eq
Some examples of valid identifiers are:
nameNameNAME_namename123_name123Name_123
Data Types
Data types are used to define the type of data that a variable can store. You can’t declare a variable without specifying its data type. here are some of the primitive data types in C++:
| Data Type | Description | Size (bytes) | Range |
|---|---|---|---|
short | A whole number | 2 | -32,768 to 32,768 |
int | A whole number | 4 | -2,147,483,648 to 2,147,483,647 |
long | A whole number | 4 | -2,147,483,648 to 2,147,483,647 |
float | A decimal number | 4 | -3.4 x 1038 to 3.4 x 1038 |
double | A decimal number | 8 | -1.7 x 10308 to 1.7 x 10308 |
char | A single character | 1 | A-Z, a-z, 0-9, special characters |
bool | A boolean value | 1 | true or false |
string | A sequence of characters | 1 per character | N/A |
The short, int, and long data types are used to store whole numbers. The float and double data types are used to store decimal numbers. The char data type is used to store a single character which are enclosed in single quotes ''. The bool data type is used to store boolean values which are either true or false. The string data type is used to store a sequence of characters which are enclosed in double quotes "".
auto Keyword
The auto keyword is used to automatically determine the data type of a variable based on the value assigned to it. Here is an example of using the auto keyword:
auto number = 10; // The data type of number will be automatically determined based on the value 10As much as possible, avoid using the auto keyword as it can make your code less readable and harder to understand.
References
References are used to refer to the same memory location as another variable. They are declared by using the & symbol after the data type. Here is an example of using references:
int number = 10;int &ref = number; // ref is a reference to the variable numberIn the example above, ref is a reference to the variable number. Any changes made to ref will also affect number.
Pointers
Pointers are used to store the memory address of a variable. They are declared by using the * symbol before the variable name. Here is an example of using pointers:
int number = 10;int *ptr = &number; // ptr is a pointer to the variable numberIn the example above, ptr is a pointer to the variable number. The & symbol is used to get the memory address of the variable number.
Variables
Variables are names given to memory locations that you will be utilizing in order for you to store data. You can change the value of a variable as you go along in your coding but as mentioned earlier, a variable should be declared first at the start of the program before you can use it. As for conventionality, if a variable name you want to use is consisted of two or more words, use small letters to the first word then capitalize the first letter/s of the succeeding word/s. The variable will appear like it has humps thus, it is said to be using camel case format.
To declare a variable, you need to specify its data type followed by the variable name. Here is the syntax for declaring a variable:
data_type variable_name;Here is an example of declaring a variable:
int userAge; // Declares a variable named userAge that can store whole numbersfloat balance; // Declares a variable named balance that can store decimal numberschar letter; // Declares a variable named letter that can store a single character, numbers, or special charactersIf you’re using multiple variables of the same data type, you can declare them in a single line like this:
Instead of:
int num1;int num2;int num3;You can do:
int num1, num2, num3;Initializing Variables
When you declare a variable, you can also initialize it with a value. Here is the syntax for initializing a variable:
data_type variable_name = value;Here is an example of initializing a variable:
int userAge = 20; // Declares a variable named userAge and initializes it with the value 20float balance = 100.50; // Declares a variable named balance and initializes it with the value 100.50char letter = 'A'; // Declares a variable named letter and initializes it with the value 'A'Constants
A constant is an identifier which can store unchanging values. The same thing as in variables, constants should be declared first at the beginning of your program before you can utilize them. You can declare constants before the main method of a C++ program like this:
#define PI 3.14159#define MAX_VALUE 100If you want to declare a constant inside the main method, use the following syntax:
const data_type CONSTANT_NAME = value;To easily distinguish a constant from variable, use capital letters when naming constants. If two or more words are used, separate the words with underscores _.
Assignment Statements and Expressions
As seen earlier, you can assign values to variables using the assignment operator =. Here are some examples of assignment statements:
numberInput = 519; // Syntax: Variable = ValueluckyNumber = numberInput; // Syntax: Variable = Variableresult = numberInput * 5; // Syntax: Variable = ExpressionNotice that in the assignment statement, the variable is located at the left of the assignment operator. The right side, however, can be a value, another variable or an expression. An expression in C++ is a combination of variables, constants, and operators that the compiler evaluates to produce a single value. Here are some examples of expressions:
Increment/Decrement Operators
A variable can have an increment or decrement. Increment is the process of increasing the value of a variable by addition. The usual increment is by 1:
number = number + 1;This can be shortened to:
number++;On the other hand, decrement is the process of decreasing the value of a variable. Just like in the increment, the usual value of decrement is 1. For example:
number = number - 1;This can be shortened to:
number--;Increment and decrement can also use other numbers aside from 1. If variable x is incremented by 3, the corresponding statement will be like this.
x = x + 3;This can be shortened to:
x += 3;Consequently, if variable y is to be decremented by 5, the statement will be:
y = y - 5;This can be shortened to:
y -= 5;Mathematical Operators
Here are some of the mathematical operators in C++:
| Symbol | Name | Operation | Function |
|---|---|---|---|
+ | Plus | Addition | Used in getting the sum of the numbers |
- | Minus | Subtraction | Used in getting the difference of the numbers |
* | Asterisk | Multiplication | Used in getting the product of the numbers |
/ | Slash | Division | Used in getting the quotient of the numbers |
% | Modulo | Modulus | Used in getting the remainder of the division |
Order of Precedence
When you have multiple operators in an expression, the order of precedence is followed. Here is the order of precedence of the operators in C++:
| Level | Operators |
|---|---|
| 1 | () |
| 2 | * / % |
| 3 | + - |
This means that operators in level 1 are evaluated first before operators in level 2 and so on. Although, usually I wrap the operations in parentheses () to make sure that the operations are done in the order that I want. So if I want to add two numbers first before multiplying them, I would write the expression like this:
result = (num1 + num2) * num3;