C++ Variable
In C++, a variable is a named memory location that stores a value. The value stored in a variable can be changed during the execution of a program. The syntax for declaring a variable in C++ is:
data_type variable_name;
Here, data_type
is the type of the variable and variable_name
is the name of the variable. For example, to declare a variable of type int
with the name my_var
, we would write:
int my_var;
Here are some examples of different variable types in C++:
int age = 25; // integer variable to store age double price = 9.99; // double variable to store price char letter = 'A'; // character variable to store a single letter bool flag = true; // boolean variable to store true or false
We can also declare multiple variables of the same data type in a single statement, separating each variable name with a comma:
int x, y, z;
Variables can be initialized with a value at the time of declaration, like in the examples above, or they can be assigned a value later in the program. For example:
int x; // declare the variable x = 5; // assign the value 5 to x
Variables can also be used in expressions and as arguments to functions:
int a = 10; int b = 20; int sum = a + b; // sum is 30 cout << "The sum of " << a << " and " << b << " is " << sum << endl;
Finally, variables can have different levels of visibility or scope. A variable declared within a function or block of code is local to that function or block and is not accessible outside of it. A variable declared outside of any function or block is a global variable and can be accessed from any part of the program.
// global variable int g_var = 10; int main() { // local variable int l_var = 5; // accessing global variable cout << "Global variable value: " << g_var << endl; // accessing local variable cout << "Local variable value: " << l_var << endl; return 0; };
In general, variables are an essential concept in programming and are used extensively to store and manipulate data in C++ and many other programming languages.