Variables in C++
A
variable is a name which is associated with a value that can be changed.
Syntax of declaring a variable in C++
Data_type vriable_name=value;
For example:
int num=20;
Types of variables
Variables
can be categorised based on their data type.
int: These type of of variables holds integer value.
char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’
etc.
bool: holds boolean value true or false.
double: double-precision floating point value.
float: Single-precision floating point value.
Types of variables based on their scope
we have
understood what is scope. Lets move on to the types of variables based on the
scope.
1. Global variable
2. Local variable
Fig: variable in c++ |
Global
Variable
A
variable declared outside of any function (including main as well) is called
global variable. Global variables have their scope throughout the program, they
can be accessed anywhere in the program, in the main, in the user defined
function, anywhere.
Global variable example
#include<iostream.h>
using
namespace std;
//this
is a global variable
char
myvar=’A’;
int
main()
{
cout<<”value
of myVar:”<<myVar<<endl;
myVar=’Z’;
count<<”value
of myVar:”<<myVar;
return
0;
}
Output:
Value
of myvar: A
Value
of myVar: Z
Local
variable
Local
variables are declared inside the braces of any user defined function, main
function, loops or any control statements(if, if-else etc) and have their scope
limited inside those braces.
Local variable example
#include<iostream.h>
using
namespace std;
char
myFun()
{
//this
is a local variable
char
myvar=’A’;
}
int
main()
{
cout<<”value
of myVar:”<<myVar<<endl;
myVar=’Z’;
count<<”value
of myVar:”<<myVar;
return
0;
}
Output:
Compile time error,
No comments:
Post a Comment