C++ Variables
NOTE: This article is part of a C++ guide, therefore only C++ code will be displayed.
Variables in C++ have two main properties: their type and their value. Types inform the computer the type of information the variable will hold, while the value is the value that the variable holds.
Types
Types can be almost anything, and they can even be declared in a program. There are however some fundamental types in C++. These include the following:
Type | description |
---|---|
int | integer. Has a size of 32 bits, allowing it to store numbers up to (specifically from to ). |
long long | Integer. Has a size of 64 bits, allowing it to store numbers up to (specifically from to ). |
float | Decimal number (i.e. , , , etc.). Has decent accuracy. |
double | Decimal number like float. Preffered over float for its greater accuracy. |
Declaring Variables
Declaring a variable means we are announcing its existance. We can then use the variable anywhere after we defined it. There are two main ways to declare a variable:
type variable;
Where the value of the variable can be set later
type variable = value;
where we specify the value of the variable on its creation.
If we want to initialize multiple variables of the same type we can use the following syntax:
type variable1, variable2, variable3;
Example Program
using namespace std;
// the int part of main is due to it being a special function in C++
int main(){
int x;
x = 10; // x = 10
int y = x; // y = 10, x = 10
y = y + 10; // y = 20, x = 10
y += x; // y = 30, x = 10
// there is also the special syntax of variable++, which increases that variable by 1
x++;
// this is equivalent to
x += 1;
// or
x = x + 1;
}