C++ Tutorial: Variables
Syntax
To declare a variable in C++, use the following syntax:
data_type variable_name;
Example
#include <iostream>
int main() {
int my_variable = 10;
std::cout << "Value of my_variable is " << my_variable << std::endl;
return 0;
}
Output
Value of my_variable is 10
Explanation
Variables in C++ are used to store values of various data types, including int, float, char, bool, and more. In the example above, we declared a variable my_variable
of type int
and assigned it a value of 10
. We then printed the value of my_variable
to the console using std::cout
.
Use
Variables are used in C++ to store data that can be manipulated and used throughout the program. They can be used in calculations, comparisons, and assignments.
Important Points
- Variables must be declared with a data type before they can be used.
- Variables can be initialized with a value when they are declared.
- The value stored in a variable can be changed throughout the program.
- Variables can be used in calculations, comparisons, and assignments.
Summary
In this tutorial, we learned how to declare and use variables C++. We learned about the syntax for declaring variables, initializing variables with values, and printing the value of variables to the console. We also learned about the importance of variables in storing data that can be manipulated and used throughout our programs.