Declaration of Variables in c++
we know that in c all variables must be declare before they are used in executable statements. this is true with c++ as well , so in c++ also we have to declare variable before use these in c++. there is a significant difference between c and c++ programming languages with regard to the place of their declaration in the program. and c language requires all the variables to be defined at the beginning of a scope. when we read a c program, we usually come across a group of variables declarations at the beginning of each scope level. their actual use appears else where in the scope, sometimes far away from the place of declaration. before the using a variable, we should go back to the beginning of the program to see whether it has been declared , if so , of what type
in c++ language allows the declaration of a variable anywhere in the scope. it means that a variable can be declared right at the place of its first use. This makes the program much easier to write and reduce the errors that may be caused by having to scan back and forth. it also makes the program easier to understand because the variable are declared in the context of their use.the example below
<iostream>
main()
{
a;
i;
sum=0;
for(i=1;i<7;i++)
{
std::cin>>a;
sum=sum+a;
}
average;
average=sum/i;
std::cout << average;
0;
}
|
Dynamic Initialization of variables
in c language, a variable must be initialized using a constant expression, and the c compiler would fix the initialization code at the time of compilation(static binding). c++ however permits or(facility) initialization of the variables at run time. This is referred to as dynamic initialization. in c++ language a variable can be initialized at run time using the expressions at the place of declaration , for example in the below following are valid initialization statements for example:
………………
………………
n=strlen(string);
……………….
……………….
area=3.1415 * rad * rad;
|
thus both the declaration and the initialization of the variable can be done simultaneously at the place where the variable is used for the first time. the following two statements in the example of the previous section
can be combined into a single statement
dynamic initialization is extensively used in object- oriented programming , we can create exactly the type of object needed using information that is known only at the run time.