Friday, April 2, 2010

Lesson 03 – Variables

So far you have learned how to write a simple program using basic C++ concepts. Here going to discuss about the variables in C++. Variables used to store data and their existing various types of variables (Eg: char, int, float etc) to store different types of information. Each of these variable types is each a keyword that you use when you declare a variable. Using the right variable type can be important for making your code readable and for efficiency.

The syntax used to declare a variable is "type ;".

Eg: char letter;

float the_float;

int a, b, c, d;

A variable in C++ must be declared (the type of variable) and defined (values assigned to a variable) before it can be used in a program. In C++, all language keywords, all functions and all variables are case sensitive. So word ball and Ball are different keywords.

Scope of variables:

The scope of a variable can be classified in to two categories naming global and local variables.

Local variables - Local variables can be only accessed within the code itself and not outside of the function. So the scope of a local variable is limited to the function in which the variables are declared.

Global variables – Global variables can be used within and outside of any function in the program. To cater this requirement the variables are declaring outside of a function block.

For Eg:

#include

using namespace std;

int iValue1 = 1; // Global variable

int iValue2 = 2; // Global variable

int main()

{

char zCh('B'); // Local variable

cout << "Value of global variable iValue1:" << iValue1 << endl;

cout << "Value of global variable iValue2:" << iValue2 << endl;

cout << "Character in local variable zCh: " << zCh << endl;

int sum, number = 3; // Local variables with and without initialization

sum = number + 5;

cout << "Value of sum: " << sum << endl;

getchar();

return 0;

}

No comments: