Tuesday, 31 March 2015

Scope of variables in C++ vs Java

The scope of a variable could be defined as the places where the variable is accessible. For the following program, both C++ and Java behaves exactly in the same way. The curly braces divides the scope of the variables, and any variable out of scope would not be available for use.

{
int x = 12;
// Only x available
{
int q = 96;
// Both x & q available
}
// Only x available
// q is "out of scope"
}

But there is a slight difference when it comes to declaring two variables with the same name in nested scopes. Refer to the following piece of code

{
 int x =12;
      {
          int x = 13;
      }
}

The above code is perfectly valid in C++, but not in Java. In C++ within the nested scope x always refers to the value 13, but out of the nested scope x becomes 12. In Java the compiler will announce that the variable x has already been defined. Thus the C and C++ ability to “hide” a variable in a larger scope is not allowed, because the Java designers thought that it led to confusing programs.

No comments:

Post a Comment