Breaking News

Declaration of Variables In C++

To declare a variable this format is used
 
Syntax: data type name;
 
To declare a signed/unsigned variable place these modifiers before the data type. Example:
 
signed int a;
 
unsigned short b;
 
To declare a signed/unsigned variable place these modifiers before the data type.
 
Example:
 
signed int a;
unsigned short b;
 
here are three places where a variable can be declared: local, formal parameters and local.
 
Local Variables
 
Variables declared within a function are called local variables. They are also sometimes calledautomatic variables.
 
These variables can be used only within the block (or function) in which they are declared. A block starts with an opening curly brace and ends in a closing curly brace.
 
A local variable is created upon entry into the block and destroyed when the program exits that block.
 
For example:
 
void test ( )
{
// Start of block
int q;
q = 2;
}
// End of block
 
void test2 ( )
// Start of another block
{
int q;
q = 5;
}
 
The two q’s that We have declared in the two functions (test and test2) have no relationship with each other. Each q is known only within its own block (since it is a local variable).
 
The main advantage is that a local variable cannot be accidentally altered from outside the block.
 
Global Variables
 
These variables are known throughout the program. They can be used by any part of the program and are not limited like local variables.
 
They are declared outside the main function.
 
#include<iostream.h>
int count; // count is a global variable
int main ( )
{
…..
}
 
Global variables will take up more memory because the compiler has to always keep it in memory.Avoid using too many global variables.
 
Use it only if the variable is going to be used by a number of functions.
 
Scope of variables
 
Variable can be either of global or local range.
 
A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block.
 
Global variables can be referred from wherever in the code, even within functions, whenever it is after its declaration.

Check Also

Insertion & Extraction In C++

Insertion is the operation of sending characters to a stream, expressed by the overloaded insertion …