With the declaration we name a variable and make it known to the compiler. Since each variable name of a data type must be unique, the compiler can also catch the error when trying to declare two variables with the same type and the same name.
The definition means that a memory area is allocated to a variable. The memory area has a unique address and is used to store values. However, a declaration without definition can also take place. Then both concepts are combined.
If we have declared a variable, it has a random value – depending on what is currently in the allocated memory area. Normally you don’t want to work with such random values. Therefore we can use initialization to set the variable to an initial value. Variables should always be initialized to avoid working with a random value.
Line | Description |
---|---|
1 | include <iostream> header that defines the standard input/output stream objects |
2 | Namespaces allow to group entities like classes, objects and functions under a name. |
4 | Declaration of the main() function with the return value int |
6 | Declaration of variable integerNumber |
9 – 19 | Declaration and initialization of different variables of different data types |
22 | Initialize the variable integerNumber with the value 1000000000 |
25 – 37 | Outputs one variable per line |
#include <iostream>
using namespace std;
int main () {
// variable declaration
int integerNumber;
// variable declaration & initialization
short shortNumber = 10000;
unsigned int unsignedInteger = 10;
long longNumber = 10000000000;
unsigned long unsignedLong = 234342;
double doubleNumber = 5.534;
long double longDouble = 53453.534;
float floatNumber = 6.767f;
char symbol = 'c';
bool isBoolean= true;
string charString = "My first string";
int myArray[] = {16, 24, 35, 41};
// variable initialization
integerNumber = 1000000000;
// variables output
cout << shortNumber << "\n"
<< integerNumber << "\n"
<< unsignedInteger << "\n"
<< longNumber << "\n"
<< unsignedLong << "\n"
<< doubleNumber << "\n"
<< longDouble << "\n"
<< floatNumber << "\n"
<< symbol << "\n"
<< isBoolean << "\n"
<< charString << "\n"
<< myArray[3] << "\n"
<< endl;
}
10000
1000000000
10
10000000000
234342
5.534
53453.5
6.767
c
1
My first string
41