Richard Heathfield wrote:
>
> Boltar said:
>
> > By accident I came across a bug like this in some Linux code I'd
> > written today. All that had happened is I forgot the "else" yet the
> > code still compiled and ran. A simplified example is below.
> >
> > #include <stdio.h>
> >
> > main()
> > {
> > int a;
> > if (1 == 1) a = 1;
> > {
> > a = 2;
> > }
> > printf("a = %d\n",a);
> > }
> >
> > When run it will print "a = 2". Should it compile at all or is GCCs
> > parser broken?
>
> It's legal.
>
> {
> a = 2;
> }
>
> is a compound statement. You can have these pretty much anywhere you can
> have an ordinary statement. If you like, you can do this:
>
> #include <stdio.h>
> int main(void)
> {
> { printf("Hello, world!\n"); }
> { puts("How are you today?"); }
> { puts("Earthquake in UK - film at 11"); }
> { return 0; }
> }
>
> Although the above is a pastiche, this facility is nevertheless useful and
> powerful, but does have the unfortunate consequence you have noted -
> forgetting an "else" doesn't necessarily give you the syntax error you'd
> have hoped for!
In case the OP (or anyone else) is wondering where this would be
useful, consider:
#if ENABLE_SOME_FEATURE
if ( new_feature_is_enabled() )
{
do_it_the_new_way();
do_another_thing_the_new_way();
}
else
#endif
{
do_it_the_old_way();
do_the_other_thing_the_old_way();
}
Compare this "clean" version to how you would have to write it if
compound statements weren't legal on their own.
--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody |
www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net |
www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <private.php?do=newpm&u=>