Memory is composed of cells that are addressed in bytes. A variable is an identifier assigned to an address (byte) or a group of addresses. When a variable is created, memory is allocated. Memory allocation refers to reserving space in memory for data or instructions during a program’s execution. Thus, when a variable is declared, a specific amount of memory, in bytes, is allocated and assigned an identifier for use in the program.
C++ identifiers follow these rules:
Can only consist of:
'a'
- 'z'
and 'A'
- 'Z'
)'0'
- '9'
)'_'
)Must begin with a letter or an underscore.
Cannot contain whitespace.
Cannot be a keyword.
Identifiers may not contain punctuation or other ASCII characters, as the compiler will reject them. Additionally, an identifier cannot start with a digit because the compiler would interpret the number as the beginning of a numeric value, causing a compilation error. Whitespace, including spaces, tabs, or newlines, is prohibited, as it would split the identifier into multiple identifiers. Keywords (reserved words) are predefined words in C++ with specific purposes and cannot be redefined, thus cannot be reused by the program as new identifiers. Some standard keywords include:
Keyword | Keyword | Keyword |
---|---|---|
alignas | alignof | and |
and_eq | asm | auto |
bitand | bitor | bool |
break | case | catch |
char | char8_t | char16_t |
char32_t | class | compl |
concept | const | const_cast |
consteval | constexpr | constinit |
continue | co_await | co_return |
co_yield | decltype | default |
delete | do | double |
dynamic_cast | else | enum |
explicit | export | extern |
false | float | for |
friend | goto | if |
inline | int | long |
mutable | namespace | new |
noexcept | not | not_eq |
nullptr | operator | or |
or_eq | private | protected |
public | register | reinterpret_cast |
requires | return | short |
signed | sizeof | static |
static_assert | static_cast | struct |
switch | template | this |
thread_local | throw | true |
try | typedef | typeid |
typename | union | unsigned |
using | virtual | void |
volatile | wchar_t | while |
xor | xor_eq |
If an identifier includes an invalid character, whitespace, or a keyword (some keyword errors may vary), a compilation error occurs:
example % g++ test.cpp test.cpp:7:8: error: expected ';' at end of declaration int n % ; ^ ; 1 error generated.
If an identifier starts with a number, the following error is typical:
example % g++ test.cpp test.cpp:7:7: error: expected unqualified-id int 1st; ^ 1 error generated.
A variable must be declared to assign a name to a memory location. Variable declaration involves specifying the data type and identifier of a variable. The syntax is:
dataType identifier, identifier, … ;
The dataType
can be any valid data type, determining the number of bytes the variable occupies and the type/range of values it can store. The identifier
must adhere to the naming rules and cannot be reused within the same scope. Multiple variables of the same type can be declared in a single statement by separating them with commas.
To declare variables of fundamental data types:
#include <iostream> using namespace std; int main() { int my_int; // Creates an integer variable long long my_long_long; // Creates a long long variable double my_double; // Creates a double variable float my_float; // Creates a float variable bool my_bool; // Creates a boolean variable char my_char; // Creates a character variable string my_string; // Creates a string variable }
Each line defines a variable of the specified type.
Variables must be declared before they are used. Consider this example:
#include <iostream> using namespace std; int main() { cout << my_int << endl; int my_int; return 0; }
In this program, my_int
is used in a cout
statement before being declared. Since the compiler reads from top to bottom, the cout
statement is encountered before my_int
is recognized. This results in a compilation error:
example % g++ test.cpp test.cpp:7:11: error: use of undeclared identifier 'my_int' cout << my_int << endl; ^ 1 error generated.
To fix this, always declare variables before using them:
#include <iostream> using namespace std; int main() { int my_int; cout << my_int << endl; return 0; }
If a variable is used before being explicitly assigned a value, such as in:
#include <iostream> using namespace std; int main() { int my_int; cout << my_int << endl; return 0; }
It will be noticed that my_int
has a seemingly random value each time the program runs. This is because memory assigned to the variable was previously used by another program, and its state remains unchanged until explicitly overwritten.
example % g++ test.cpp 985495345 example % g++ test.cpp 24654876
To avoid unpredictable values, always initialize, or give a value for the first time, variables with an explicit value (explained here):
int my_int = 0;
This ensures the variable starts with a known value rather than an arbitrary one.
Variable - A name (identifier) given to an address (byte) or grouping of addresses in memory. When a variable is created, memory is allocated.
Memory Allocation - The process of reserving memory space for data or instructions during a program’s execution.
Identifier - A user-defined name assigned to a variable, function, or other entities in C++.
Keywords (Reserved Words) - Predefined words in C++ that have a specific meaning and cannot be redefined by the programmer.
Whitespace - Spaces, tabs, and line breaks.
Variable Declaration - The process of defining a variable by specifying its data type and identifier.
What is a variable in C++?
What happens when a variable is created in C++?
What is memory allocation in the context of variables?
Why is memory allocation important when declaring variables?
What is an identifier in C++?
What characters can be used in a C++ identifier?
What are the rules for naming identifiers in C++?
Why can't an identifier start with a digit?
Why can't an identifier contain whitespace?
What happens if an identifier contains an invalid character?
What error occurs if an identifier starts with a number?
What are keywords in C++?
Why can't keywords be used as identifiers?
Can keywords be redefined by the programmer?
What are some examples of C++ keywords?
What kind of error occurs if a keyword is mistakenly used as an identifier?
What does it mean to declare a variable in C++?
What is the syntax for declaring a variable?
What are the components of a variable declaration?
How does the dataType
affect a variable?
Can multiple variables be declared in a single statement? If so, how?
Why must a variable be declared before it is used?
What happens if a variable is used before being declared?
What kind of error occurs when an undeclared variable is used?
How can you ensure a variable is properly declared before use?
What does it mean to initialize a variable?
Why is it important to initialize variables?
What happens if a variable is used before it is initialized?
Why do uninitialized variables sometimes display random values?
How can you ensure a variable always starts with a known value?
What does the following code do?
int my_int; cout << my_int << endl;
Why does the output of an uninitialized variable change each time the program runs?
What does the following error mean?
test.cpp:7:11: error: use of undeclared identifier 'my_int'
How can you modify a program to prevent the use of an undeclared variable?
What will happen if you declare multiple variables of the same type on a single line?
Why is it important to understand how memory is assigned to variables?
What error will occur in the following code, and why?
int main() { int 1variable; return 0; }
How can it be fixed?
What error will be produced by the following code?
int main() { int my var; return 0; }
How can it be fixed?
What compilation error will result from this incorrect variable declaration?
int main() { double myDouble return 0; }
How can it be fixed?
What happens if a variable is declared twice in the same scope?
int main() { int num; int num; return 0; }
What error message will the compiler generate? How can it be fixed?
What error will occur if a variable is used before being declared?
int main() { cout << myNumber << endl; int myNumber; return 0; }
Why does this happen? How can it be fixed?
What error does the following code cause?
int main() { int num; cout << num << endl; return 0; }
Why does the output vary each time the program is executed? How can it be fixed?
What will happen if a variable is declared without a type?
int main() { myVariable; return 0; }
How can this be corrected?
What error will occur in the following code due to using a keyword as an identifier?
int main() { int return; return 0; }
How does the compiler handle this situation?