• Have Any Question?
  • contact@eitworld.com

cpp variable





C++ Variable

  • A variable is a data name given to a data value stored in the memory.
  • The value of variable can vary at the time of execution.
  • Name of the variable should be meaningful and in C++ there are some rules are defined for naming variables which are as follows:

Rules for naming variable

  • Variable name may contain letters, digits and underscore (_) character.
  • The variable name can begin with the letters as well as with underscore (_) character.
  • A variable name should not start with digit.
  • A variable name cannot contain punctuation characters like (@,#,$,%,^,&,* etc)
  • A variable name cannot be a keyword.
  • The variable names may be a combination of uppercase and lowercase characters. For example name and naME are not the same. Both are different.

Declaration of Variables

    • We must declare the variable before using it into the program.
    • A variable is declared using a data type and a meaningful variable name. The basic syntax of variable declaration is as follows:

Data_type variable_name;
    • A variable can be of any data type like int, float, double and char etc.
    • Here are some examples of variable declaration:

int age;
float area;

char m;

int a,b,c;/*More than one variable of same type can be declare in single statement.*/

Initializing Variables

    • Variable can be initialized using the assignment operator ‘=’.
    • Variable declaration and initialization can also be performed in same line.
    • The basic syntax to initialize a variable is as follows:

variable_name=data_value;
—-OR—–

Data_type variable_name=data_value;

    • Here is an example of variable initialization:

int x;
x=3;

—-OR—-

int x=3;

    • Here is an example of using variable in C++ program:

Example


#include<iostream.h>
int main()

{

int a;/*Variable declaration*/

a=5;/*Variable initialization*/

cout<<“nvalue of a is:”<<a;

return 0;

}

    • The output of the above program is as follows:

Output


value of a is:5


Real Time Web Analytics