C++ Variables/Literals

A variable in C++ is a named memory region with the ability to store values of a certain data type. On the other hand, a literal is a constant value that is used immediately within the program and isn’t saved in a variable.

Variables can be declared and initialized in the following way:

dataType variableName = value;

Here, the variable’s data type is indicated by dataType, its name is indicated by variableName, and its initial value is shown by value.

Example:

int x = 5;
int y = 10;
double z = 3.14;

Literals can be of several data kinds, including boolean values, characters, integers, and floating-point numbers. They do not need to be kept in a variable and can be written straight in the program. The code below, for instance, uses a variety of literals:

int a = 10;            // integer literal
float b = 3.14;        // floating-point literal
char c = 'A';          // character literal
bool d = true;         // boolean literal
string e = "hello";    // string literal

Here, the variables a and b are set to their initial values: 10 for variable a, 3.14 for variable b, ‘A‘ for variable c, true for variable d, and ‘hello‘ for variable e.

It is crucial to remember that unlike variables, which can receive new values whenever necessary, literals have a fixed value and cannot be modified while a programme is running.

In C++ programming, variables and literals are essential ideas that are heavily utilised while developing programmes.

This statement declares a constant named “PI” with a value of 3.14. The value of the constant cannot be changed during program execution.