Friday, July 31, 2009

Is it legal in C++ to declare a variable in one function which has the same name as a variable declared ??

Is it legal in C++ to declare a variable in one function which has the same name as a variable declared in another function? How are the two variables related? If the value of one of these variables is changed, what effect is apparent in the other variable?

Is it legal in C++ to declare a variable in one function which has the same name as a variable declared ??
As long as they are not in the same scope it is fine. Example:





void f(int a, int b) {


int i;


int a; // Illegal - a has already been defined in this scope





for(i=0 to 100) {


int a = i; // Legal - inside the loop is a new scope


int b = ::a; // Legal - different b which is referring to the original a passed into the function


}


}





To access the same variable name in a higher scope, use the scope resolution operator '::' (See above)





void g(int a, int b) {


int i; // Legal - there is no relationship between this i and the i of function f()


}
Reply:Not illegal but can lead to some problems at runtime wherby u mite not get the desired results





consider a function calling another function. if the variable has been declared first in the outside func and also inthe inner function they there will be data probs
Reply:If you simply declare the variables in different functions, it will be legal (unless you declare them public, which changes your scope)





You can always read more on Scope, this will be clearly explained.


No comments:

Post a Comment