WHAT IS VARIABLES?
A variable provides named storage that manipulate the program. The name of a variable is called an identifier. It should be related name. You can give a variable any name you want, as long as it is a valid identifier. Variables are used to store data. Every C++ variable has a:
Name -- variable
name like price
Type -- variable
type like integer, string
Size -- determined
by the type
Value -- the data
stored in the variable's memory location
Address -- the starting
location in memory where the value is stored
Syntax:
data_type variable_name;
data_type variable_name1,
variable_name2, variable_name3;
Example:
/* variable definition */
int
marks;
char
ch;
float
unit;
double meter_to_cm;
Example:
Example:
Example:
Example:
Example:
float char; // char is keyword and not allowed variable name
Variables Declaration in C++
C++ Declaration requires every variable to be declared with its type before its first use.
int marks;
Variable Initialization in C++
Variables can be initialized and initial value can be assigned along with their declaration.
int marks=600;
int price,tax; //For declaration multiple variables;
RULES FOR NAMING VARIABLES
·
Variable name range in environment 1 to 31 character and in Visual C++
can range from 1 to 255 characters Variable names.
Example:
float productCost; //range 11
·
All variable names must start with an alphabet or an Underscore ( _
).
Example:
char _price;
float cost;
·
After the first initial letter, variable names can also contain numbers.
Example:
double a1, a3;
·
No spaces or special characters, however, are allowed.
Example:
float product price //wrong variable name with space
·
Uppercase characters are distinct from lowercase characters.
Example:
float PRICE;
float price;
·
You cannot use a C++ keyword (reserved word) as a variable name , for
check C++ reserve keyword click here
Example:
float char; // char is keyword and not allowed variable name
SCOPE OF VARIABLE IN C++
A scope is a region of
the program and broadly speaking there are two places, where variables can be
declared.
Local Variable
Variables that are
declared inside a function or block are local variables. They can be used only
by statements that are inside that function or block of code.
Example of Local
Variable
#include <iostream> //header file
using namespace std;
int main () { //main
float price; //Local variable declaration:
cout << price; //output
return 0;
}
Global Variable
Global variables are
variables that are often declared outside the main() function.
The variable scope is the full file where the variable is defined.
The global variable can
be defined as below.
Example of Global
Variable
#include <iostream> //header file
using namespace std;
float price; //Global variable declaration:
int main () { //main
cout << price; // output
return 0;
No comments:
Post a Comment