Variables

Variables

Variables are parts of memory whose value can change. Variables have user defined names consisting of number and character literals. Variables are of certain type. Types define and represent values. Variables are declared before they are used following the type variable_name = {value} rule.

#include <iostream>
int main(){
	int x;
}

This example declares an integer variable named x. To declare and initialize a variable we use:

#include <iostream>
int main(){
	int x = 123;
}

Types

Some of the fundamental types are int for integer numbers, double for real numbers, char for characters and bool for boolean values:

#include <iostream>
int main(){
	int x = 123;
	double d = 456.78;
	char c = 'A';
	bool f = true;
}

Examples

We can initialize the variable and reassign the value:

#include <iostream>
int main(){
	int x = 123;
	x = 456;
	x = 789;
}

We can declare multiple variables of the same type on the same line:

#include <iostream>
int main(){
	int x, y, z;
	x = 1;
	y = 2;
	z = x + y;
}

We can print out variables values:

#include <iostream>
int main(){
	int x = 123;
	double d = 456.78;
	char c = 'C';
	std::cout << "x is: " << x << std::endl;
	std::cout << "d is: " << d << std::endl;
	std::cout << "c is: " << c << std::endl;
}