int bar = 2;
if (bar)
{
int bar;
}
Neither gcc or Clang manages to issue a warning (or error) for this, and the program crashes immediately on launch. Is there a good reason for this? It doesn't seem like it would be something hard to catch. It's the basics of block scoping: the nested scope inherits the names of the enclosing block...
Any explanations?
EDIT: It turns out the crash was due to using Clang. I've tested many times back and forth, and it seems certain that the combination of the variable redefinition and Clang causes the crash. However, I haven't been able to reproduce the crash in a test project, so go figure.
The problem turned out to be Objective-C related. As Jonathan Leffler points out doing ´int bar = bar´ in the inner scope initializes the variable from itself, and that's what causes the problem, when the initialization is done via an Objective-C method call.
The following shows the bug in action:
-(void)crasher
{
NSNumber* bar = [NSNumber numberWithInt:2];
if (bar)
{
NSString* bar = [self doit:bar];
}
}
-(NSString*)doit:(NSNumber*)num
{
NSString* str = [num stringValue]; // This line causes the crash
return str;
}
Note that doing something similar in pure C does not produce a crash:
int bar = 2;
if (bar)
{
char buff[10];
int bar = sprintf(buff, "%d",bar);
}