Gavin Sinclair <gsinclair / soyabean.com.au> writes:

> On Thursday, January 30, 2003, 11:13:45 AM, Paul wrote:
>
>> On Thu, Jan 30, 2003 at 08:35:01AM +0900, Gavin Sinclair wrote:
>>> The behaviour exhibited by that snippet always struck me as
>>> "surprising", coming from C-like languages where "if" introduces a new
>>> scope.
>
>> In C, "if" doesn't introduce a new scope; {} does:
>
>> void foo() {
>>   int x = 1;
>>   if(1)
>>     int x = 2; // error: redeclaration of x
>>   if(1) {
>>     int x = 2; // okay; the outer x is hidden by this one
>>   }
>> }
>
> Now *that* is surprising!  I assumed that the braceless (one-line)
> version of "if" (and other control statements) was a typographical
> shortcut only.
>
> You learn something every day...

And just to make the point even clearer: in C, braces define a new scope
even without an "if" ...

  int main() {
    int x = 1;
    printf("before braces: x == %d\n", x);
    {
      int x = 2;  // no error
      printf("inside braces: x == %d\n", x);
    }
    printf("after braces:  x == %d\n", x);
    return (0);
  }

Running this program gives these results:

  before braces: x == 1
  inside braces: x == 2
  after braces:  x == 1


-- 
 Lloyd Zusman
 ljz / asfast.com