|
|
|
|
|
Explanation:
|
#include <stdio.h>
int main( int argc, char* argv[] )
{
/* Outer scope */
double r = 3.14; /* (1) */
printf( "1. r = %lf\n", r ); /* Access r(1) */
{ /* Inner scope (a new scope !) */
printf( "2. r = %lf\n", r ); /* Access r(1) */
double r = 4.444; /* (2) */
printf( "3. r = %lf\n", r ); /* Access r(2) */
}
printf( "4. r = %lf\n", r ); /* Access r(1) */
}
|
Result:
1. r = 3.140000 2. r = 3.140000 3. r = 4.444000 4. r = 3.140000 |
How to run the program:
|
So this example is illegal in Java:
public class scoping1
{
public static void main( String[] args )
{
double r = 3.14;
{ /* Inner scope (a new scope !) */
int r = 4; /* Illegal in Java */
}
}
}
|
Gosling (designer of Java) thinks that variables with the same name inside one function is too confusing....
|
How to run the program:
|
|
|
void func( double r )
{
{ /* Start of a new scope */
/* NOTE: without this inner scope, you will get error:
'r' redeclared !!! */
printf( "1. r = %lf\n", r ); /* Access parameter r */
double r = 4.444; /* (1) */
printf( "2. r = %lf\n", r ); /* Access r(1) */
}
}
int main( int argc, char* argv[] )
{
func( 3.14 ); // Pass 3.14 into parameter variable r
}
|
Result:
1. r = 3.140000 2. r = 4.444000 |
How to run the program:
|
|
Reason:
|