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);
}
There's nothing to catch here. The variable in the inner block is a completely different variable, that hides the variable in the outer block. This is a perfectly standard feature of the language that has been there since the beginning of times.
The crash you are experiencing has absolutely nothing to do with the code you posted. Unless you made a mistake in your code, working with the inner variable while assuming that your are working with the outer one.
It is the basic of nested scope: inside a nested scope you can shadow something declared in an outer scope. gcc has an option to get a warning for this (-Wshadow), but it isn't activated either by -Wall nor -Wextra: the warning can appear without change in the code (an header has now a definition at global scope for an identifier used in a function).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With