C++ Variables C-PLUS-PLUS
- C++ Introduction
- C++ Syntax
- C++ Output (cout <<)
- C++ Comments
- C++ Variables
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ If Else
- C++ Switch
- C++ While Loop
- C++ Do/While Loop
- C++ For Loop
- C++ Break and Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Functions Parameters
- C++ Function Overloading
- C++ OOP
- C++ Classes and Objects
- C++ Class Methods
- C++ Constructors
- Destructors in C++
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Polymorphism
- C++ Files
- C++ Exception Handling
C++ Variables
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords), for example:
int
- stores integers (whole numbers), without decimals, such as 123 or -123double
- stores floating point numbers, with decimals, such as 19.99 or -19.99char
- stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotesstring
- stores text, such as "Hello World". String values are surrounded by double quotesbool
- stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
Syntax
Where type is one of C++ types (such as int
), and variable is the name of the variable (such as x or myName). The equal sign is used to assign values to the variable.
Create a variable called myNum of type int
and assign it the value 15:
cout << myNum;
You can also declare a variable without assigning the value, and assign the value later.
Example
#include <iostream>
using namespace std;int main() {
int myNum;
myNum = 15;
cout << myNum;
return 0;
}
Output:
15
Constants
You can add the const
keyword if you don't want to override existing values (this will declare the variable as "constant", which means unchangeable and read-only).
You can't change the value of constants during the program. You just can define its value at once during declaration.
Example
#include <iostream>
using namespace std;int main() {
const int myNum = 15;
myNum = 10;
cout << myNum;
return 0;
}
Output:
In function 'int main()':
6.9: error: assignment of read-only variable 'myNum'