Variables in C++

 Variables in C++:

A variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory location. In C++, all the variables must be declared before use. A particular type of variable can hold only the same type of value. For example, an integer variable can hold only an integer value, a real variable can hold only a real value and a character variable can hold only a character.

Declaration of Variables:-

Declaration does two things:

1.      Tells the compiler what the variable name is,

2.      It specifies what type of data the variable will hold.

The declaration of variable is must be done before it is use in a program




Syntax:

               Data-type  variable_Name1, variable_Name2,........, variable_NameN;

Example:

               int count;

               int number1, number2, number3;

               double ratio;

Data-type in syntax represents the type of data which variable will hold. Variables are separated by commas (,). Declaration statement must ends with semicolon (;).

Rules for Declaring Variable Names:-

·        A variable name is any combination of 1 to 31 alphabets, digits or underscores.

·        The first character in the variable name must be an alphabet or underscore.

·        No commas or blanks are allowed within a variable name.

·        No special symbol other than an underscore (as in gross_sal) can be used in a variable name.

·        Uppercase and Lowercase are significant. That is the variable total is not the same as Total or TOTAL.

·        It should not be a keyword.

Initialization of Variable:

The memory location referred to by this variable holds some value. The variables once declared, are assigned some value. This assignment of value to these variables is called initialization of variables.

Initialization of a variable is of two types:

Static Initialization: The variable is assigned a value in advance i.e. at compile time is called as static initialization.

Different ways to initialize variable in C++:

Method 1: int a = 5;

Method 2: int a (5) ;

Method 3: int a{5} ;

Method 4: int a;   

                  a = 5;

Dynamic Initialization: The variable is assigned a value at the run time. The value of this variable can be altered every time the program is being run.

int a;

cin>>a; 



Comments

Popular posts from this blog

Tokens in C++

Data Types in C++