Question

I was reading C programming from a book that says all variables have to be declared in the beginning of the function. I tried following code but didn't issue any error. I am using mingw and codeblocks. The code is as follows:

#include <stdio.h>

int main()
{
    int i=10;
    printf("%d\n",i);

    int j=20;
    printf("%d\n",j);

    return 0;
}

Do I have to change any compiler setting or something to make it compatible with the standard given in the book?

I am using -std=c89 compiler option. See the compilation messages below:

-------------- Clean: Debug in HelloWorld (compiler: GNU GCC Compiler)---------------

Cleaned "HelloWorld - Debug"

-------------- Build: Debug in HelloWorld (compiler: GNU GCC Compiler)---------------

mingw32-gcc.exe -Wall -std=c89  -g     -c D:\MyCodeBlocksProjects\HelloWorld\main.c -o     obj\Debug\main.o
mingw32-g++.exe  -o bin\Debug\HelloWorld.exe obj\Debug\main.o    
Output size is 68.53 KB
Process terminated with status 0 (0 minutes, 0 seconds)
0 errors, 0 warnings (0 minutes, 0 seconds)
Was it helpful?

Solution

all variables have to be declared in the beginning of the function.

To be precise, they have to be declared in the beginning of a block. And this is only true in C89. C99 has removed this limit. So you can change your compiler to strict C89 mode. For example, for GCC, it's -std=c89 option. To obtain all the diagnostics required by the standard, you should also specify the option -pedantic.

To demonstrate what I mean by in the beginning of a block, this is legal C89 syntax:

void foo()
{
    int x = 1;
    x = x + 1;
    {
        int y = 42;  /**OK: declaration in the beginning of a block*/
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top