I declared a variable in this way:
int i = 0;
I get the warning:
ISO C90 forbids mixed declarations and code
Make sure the variable is on the top part of the block, and in case you compile it with -ansi-pedantic
, make sure it looks like this:
function() {
int i;
i = 0;
someCode();
}
Up until the C99 standard, all declarations had to come before any statements in a block:
void foo()
{
int i, j;
double k;
char *c;
// code
if (c)
{
int m, n;
// more code
}
// etc.
}
C99 allowed for mixing declarations and statements (like C++). Many compilers still default to C89, and some compilers (such as Microsoft's) don't support C99 at all.
So, you will need to do the following:
Determine if your compiler supports C99 or later; if it does, configure it so that it's compiling C99 instead of C89;
If your compiler doesn't support C99 or later, you will either need to find a different compiler that does support it, or rewrite your code so that all declarations come before any statements within the block.
Just use a compiler (or provide it with the arguments it needs) such that it compiles for a more recent version of the C standard, C99 or C11. E.g for the GCC family of compilers that would be -std=c99
.
I think you should move the variable declaration to top of block. I.e.
{
foo();
int i = 0;
bar();
}
to
{
int i = 0;
foo();
bar();
}
-Wdeclaration-after-statement
minimal reproducible example
main.c
#!/usr/bin/env bash
set -eux
cat << EOF > main.c
#include <stdio.h>
int main(void) {
puts("hello");
int a = 1;
printf("%d\n", a);
return 0;
}
EOF
Give warning:
gcc -std=c89 -Wdeclaration-after-statement -Werror main.c
gcc -std=c99 -Wdeclaration-after-statement -Werror main.c
gcc -std=c89 -pedantic -Werror main.c
Don't give warning:
gcc -std=c89 -pedantic -Wno-declaration-after-statement -Werror main.c
gcc -std=c89 -Wno-declaration-after-statement -Werror main.c
gcc -std=c99 -pedantic -Werror main.c
gcc -std=c89 -Wall -Wextra -Werror main.c
# https://stackoverflow.com/questions/14737104/what-is-the-default-c-mode-for-the-current-gcc-especially-on-ubuntu/53063656#53063656
gcc -pedantic -Werror main.c
The warning:
main.c: In function ‘main’:
main.c:5:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
int a = 1;
^~~
Tested on Ubuntu 16.04, GCC 6.4.0.
To diagnose what really triggers the error, I would first try to remove = 0
If the error is tripped, then most likely the declaration goes after the code.
If no error, then it may be related to a C-standard enforcement/compile flags OR ...something else.
In any case, declare the variable in the beginning of the current scope. You may then initialize it separately. Indeed, if this variable deserves its own scope - delimit its definition in {}.
If the OP could clarify the context, then a more directed response would follow.