If you did not initialize a local variable the variable might contain a garbage value which cannot be determined (in both C++ and Java ). For example
int x;
x will not be intialized automatically to zero( if it is an instance variable, then yes it would be intialized to zero in Java).
You are responsible for assigning an appropriate value before you use x. If you forget you get a compile-time error telling you the variable might not have been initialized. (Many C++ compilers will warn you about uninitialized variables, but in Java these are errors.)
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.
{
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.
Subscribe to:
Comments (Atom)