Remove declaration-after-statement C warning
Alan Coopersmith
alan.coopersmith at oracle.com
Wed Sep 11 22:59:52 PDT 2013
On 09/11/13 10:20 PM, Mouse wrote:
>>>> It's still bad style.
>>> Yeah, I actually totally agree.
>
> So do I, in most cases. I can, sort of, see a place for it in things
> like macro expansions, but even then I'd rather open a new block for
> the new scope.
>
>> The one bit I would like to have is declarations in for/while loops,
>> such as
>
>> for (int i = 0; i < MAXSCREENS; i++)
>
> I wish I knew more about the spec. If that's equivalent to
>
> int i;
> for (i=0;i<MAXSCREENS;i++)
>
> then I don't like it any better. But if i goes out of scope at the end
> of the loop, then I rather like the idea.
It does limit the scope to the loop.
This compiles fine with "gcc -std=c99 test.c":
#include <stdio.h>
int main(int argc, char **argv)
{
for (int i = 1; i < argc; i++)
printf("%d: %s\n", i, argv[i]);
}
But this does not:
#include <stdio.h>
int main(int argc, char **argv)
{
for (int i = 1; i < argc; i++)
printf("%d: %s\n", i, argv[i]);
printf("%d arguments total\n", i);
}
test.c: In function ‘main’:
test.c:7:36: error: ‘i’ undeclared (first use in this function)
Of course, you could get the same by just wrapping more blocks around it:
{
int i;
for (i = 1; i < argc; i++)
printf("%d: %s\n", i, argv[i]);
}
but that's a lot uglier.
> (Even then, though, I'm not
> sure I like the syntax, because it looks as though it is going to have
> horrible parsing ambiguities in the presence of comma operators or
> multiple variable declarations in the init portion.)
Yeah, don't do those. If it's going to be hard for the compiler to work
out, it's going to be hard for the humans who have to read it & fix bugs
to work out. Places I've wanted to use it are mainly making the scope
clearer for humans & the optimizer for simple integer incrementing loops,
like:
http://patchwork.freedesktop.org/patch/11880/
However, to bring this back around to the original subject, at least with
the gcc 4.7 I have here, the -Wdeclaration-after-statement doesn't
complain about having the declaration in the loop syntax, only in the middle
of a block:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("Noisy echo:\n");
for (int i = 1; i < argc; i++)
printf("%d: %s\n", i, argv[i]);
int ret = argc;
return ret;
}
% gcc -std=c99 -Wdeclaration-after-statement test.c
test.c: In function ‘main’:
test.c:10:5: warning: ISO C90 forbids mixed declarations and code
[-Wdeclaration-after-statement]
Remove the lines after the loop and gcc is as happy as a clam, so I'm
okay having the warning in our default CFLAGS, as it still lets me have
this C99 syntax addition.
--
-Alan Coopersmith- alan.coopersmith at oracle.com
Oracle Solaris Engineering - http://blogs.oracle.com/alanc
More information about the xorg-devel
mailing list