Variables

Lesson 6
Author : Afrixi
Last Updated : November, 2022
C++ - Programming Language
This course covers the basics of programming in C++.

In C++, variables are used to store values that can be manipulated or used in calculations throughout a program. Variables in C++ have a specific data type, which determines the type of value that can be stored in the variable, as well as the operations that can be performed on that value.

Here are some common data types and examples of how they can be used:

int: Used to store integer values. For example:

int age = 25;

float or double: Used to store floating-point values (decimal numbers). float uses 4 bytes of memory, while double uses 8 bytes and has a higher precision. For example:

float pi = 3.14159;
double price = 19.99;

char: Used to store single characters. For example:

char grade = 'A';

string: Used to store text strings. For example:

std::string name = "Alice";

Variables can also be initialized with a value when they are declared, as shown in the examples above. In addition, variables can be assigned a new value using the assignment operator =. For example:

int x = 5;
x = 10;

In this code, the variable x is first initialized with the value 5, and then assigned a new value of 10.

Variables can also be used in expressions and calculations. For example:

int a = 5;
int b = 3;
int c = a + b;

In this code, the variables a and b are used in an expression that adds them together, and the result is stored in the variable c.

Note that variable names in C++ are case sensitive, and must start with a letter or underscore. They can include letters, numbers, and underscores, but cannot include spaces or special characters.