Variables in CPlusPlus


Variables in CPlusPlus

Variables in CPlusPlus are basically the memory storage holders for those values that keep on changing in a program (as general rule is applied right now ).

Variables in CPlusPlus can be categorized as

Character types: Character types are used to store a single character such as ‘A’ etc

Integer types: They store numbers such as 1 or 2012. They can be signed or unsigned (negative value can be used), depending upon the circumstances

Floating-point types: Floating points are also numeric values but they include dotted decimal notation such as 1.1, 2.53 etc

Boolean type: These types represent either true or false

Variables declaration and initialization

By declaring a variable, we tell the compiler that a variable is declares. in variable initialization, we reserves the space for that variable in memory. Example are:

// just declaring

int a, b, c;
char c, d;
float f,e ;
double d;

// declaring as well as initializing

int i = 1, j = 4;
char ch=’a’;

Constants in C++

Constants are those values that retain themselves.In other words, they do not changed when initialized. Until programmer change their values in code

// header files consists of libraries for number of functions etc
#include “stdafx.h”
#include
using namespace std;

/* We have used constant variables that won’t change in the entire execution of program
main is the heart or entry point of the C++. int represent return type integer */

int main()
{ const int i=4;
const int j=10;
// cout is for output to the screen
cout<< i*j; // new line cout<< "n"; }

Output : 40

Scope of a variable

The scope of a variable can be defined as the life of the variable within specific boundary. If we try to access that variable outside these boundaries, then it will not appear to get accessed.
This concept brings us with the definitions of local variables and global variables.

Local Variable

Local variable has the life within the block in which it has been declared/initialized.

Example

#include
using namespace std;

int main ()
{
/*Local variable declaration and initialization.
The life of ‘a’ is present inside main() block */
int a=1;

cout << a; return 0; }

Output
1

The Global Variable

A global is that variable which remains active, even if it is used in other block of code. In fact, it lives throughout the program

Example

#include
using namespace std;

// this is global variable because it is not bounded inside the method’s boundaries
int a = 10;

// heart of C++
int main ()
{

cout << a; }

Output
10

Syed Adeel Ahmed
Syed Adeel Ahmed
Analyst, Programmer, Educationist and Blogger at Technofranchise
Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.

Published by

Syed Adeel Ahmed

Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.