What are the Variables?
A variable could be a named memory location that temporarily stores data that may change while the program is running.
- The type of a variable indicates what value it’ll store. The name of a variable is its identifier.
- Assigning variables using an assignment statement is possible. Variables of various types occupy different amounts of memory space and have different sizes.
- Int, double, bool, and char are the essential C++ types.
Conditions for naming a variable name
- A variable can consist of the following alphabets, numbers, and underscore _.
- A variable name cannot begin with variety cannot have special characters or spaces.
- Variable names cannot commence with an uppercase character.
- A variable title can’t be a keyword that is a reserved word. For instance, Use the int keyword to express integers.
- The programmer can also start the variable name using underscore.
Local and global variable:
Generally, there are three spots, where variables are often declared −
- Inside a function or a block is known as local variables.
- The definition of these function parameters is named formal parameters.
- Outside of all functions of the program are called global variables.
Variables that are inside a function or block are local. They will be used only by statements that are inside that function or block of code. Local variables don’t seem to be known to a purpose outside their own.
Global variables are outside of all the functions, usually on top of the program. The worldwide variables will hold their value throughout the lifetime of your application.
What are Constants?
A constant may be a named memory location which temporarily stores data that is still identical throughout the execution of the program.
- Constants are called literals.
- Constants may be any of the info types.
- It’s considered as an easy and efficient practice to define constants using only upper-case names.
There are two different ways in C++ to define constants −
The “const” keyword
You can use the const prefix to declare constants with a particular type as follows:
const type variable = value;
In C++, utilizing the above syntax, we can build variables whose value can not be replaced. For that, we use the const keyword. Here’s an illustration:
const double PI = 3.1416;
PI = 4.6
// Error! PI is constant.
Here, we’ve used the keyword const to declare the PI value. If we try and change the PI value, an error will pop.
The #define Preprocessor
#define preprocessor ia a another way to define a constant:
#define identifier value
Data value used for representing an identifier that uniquely identifies an object
#define Sidevalue 15
areaofsquare = Sidevalue*Sidevalue;
printf(“value of areaofsquare : %d”, areaofsquare);
The above-given program is the example of defining constants using the preprocessor.