Reputation: 23341
I have a piece of code that compiles fine when I write it in this form (with the -Wjump-misses-init
flag):
int some_function(void) {
...
if (is_error)
goto error;
int a;
a = 1;
return a;
error:
return 666;
}
But when I write the same function in this form I get the below warning when I compile (:
int some_function(void) {
...
if (is_error)
goto error;
int a = 1;
return a;
error:
return 666;
}
test.c: In function 'some_function':
test.c:15:17: warning: jump skips variable initialization [-Wjump-misses-init]
test.c:21:1: note: label 'error' defined here
test.c:17:13: note: 'a' declared here
Why does GCC give me that warning when I declare and initialize a
on the same line? Seems a bit odd to me? These examples are nonsensical but I'm afraid I'm not at liberty to divulge the real code snippet. I am running GCC 4.7.2 on Debian Wheezy 7.3.
EDIT: void typo
Upvotes: 7
Views: 1758
Reputation: 158459
In C++ you are not allowed to bypasses declarations with initialization but it seems to be allowed in C99. You can have gcc
warn you about if you either use -Wjump-misses-init
or -Wc++-compat
. This is covered in the gcc
docs section Options to Request or Suppress Warnings and says:
Warn if a goto statement or a switch statement jumps forward across the initialization of a variable, or jumps backward to a label after the variable has been initialized. This only warns about variables that are initialized when they are declared. This warning is only supported for C and Objective-C; in C++ this sort of branch is an error in any case.
-Wjump-misses-init is included in -Wc++-compat. It can be disabled with the -Wno-jump-misses-init option.
Note, this also applies to declarations inside a switch statement. One way to work around this is to create a new scope using {}
.
In the Annex I the draft C99 standard suggests this as warning, it says:
An implementation may generate warnings in many situations, none of which are specified as part of this International Standard. The following are a few of the more common situations.
and includes the following bullet:
A block with initialization of an object that has automatic storage duration is jumped into (6.2.4).
Upvotes: 3
Reputation: 157314
If you were to use the a
variable after jumping to the error:
label, its value would be indeterminate (6.2.4p6); this is potentially confusing, which is why gcc warns about it. (It is also illegal in C++.)
To avoid the warning and still use declaration-initialization, you can wrap code in a block:
int some_function(void) {
{
...
if (is_error)
goto error;
int a = 1;
return a;
}
error:
return 666;
}
In this case, you would need to declare outside the block any variables that you use after the error:
label.
Upvotes: 1