How Variables & Constants are works in C++ . Variables in C++ act as a memory location, it is nonentity but the name of the ampule or component that stores the data or values that are being used in the program later for implementation.
Variables are the most significant part of any programming language. Any programming language is imperfect without a variable. We can also say that without variables, the program cannot run. In C++ any word but the keywords are used as a variable.
Type can be anything int, double, char, float, long int, short int, etc.
Rules and Regulations for Defining Variables in C++ Language
- Variables can be a combination of digits, special characters like and percent (&), underscore (_), or string.
- Upper and lower cases are preserved as different variables as C++ is a case-sensitive language.
- C++ variables must be started with the character. It will not reflect the number as a first character. 6abc is not a valid variable since it starts with the number where educba6 can be a valid variable as it started with the character.
- variables in C++ language should not be a keyword. for, this, if, else, while, do, char, this, etc are the keywords that are used for the exact purpose. These keywords cannot be used as a variable in C++.
- Blank spaces are not allowable for the variables. Edu bca is not valid as there is space between edu and bca where edubca is valid variable or edu_cba is also a valid variable as underscore sign is used to seam the variable.
Declaration and Initialization
Variable must be declared before they are used. Typically, it is favored to declare them at the starting of the program.
Scope of Variables
All the variables have their area of operative, and out of that border they don’t hold their value, this border is called scope of the variable.
For most of the cases, it’s between the curly braces, in which variable is professed that a variable exists, not outside it. We will study the storage classes later, but as of now, we can approximately divide variables into two main kinds,
- Global Variables
- Local variables
Global variables are those, which are once declared and can be used throughout the lifetime of the program by any class or any function. They must be professed outside the
Local variables are the variables which exist only among the curly braces, in which its declared. Outside that they are unobtainable and leads to compile time error.
Constants refer to fixed values that the program may not alter and they are called literals.
Constant are also called as Literals. Constant must be initialized when declared as values cannot be assigned it to later.
There can be any types of constants like integer, float, octal, hexadecimal, character constants etc.
There’s another way to define constants that dates back to early versions of the C language, the precursor of C++. The preprocessor directive #define can create a constant by specifying its name and value, separated by spaces:
#define KILLBONUS 3525