christian Martin
christian Martin

Reputation: 51

Error message Variable declaration in C

I'm new to c and I am having a hard time understanding why am I getting an error while trying to compile the following code in c I believe I tried it Java and it worked compiled perfectly without error

void f(void) {
  int i;
  i = 6;
  int j;
  j = 20;
}

Upvotes: 2

Views: 83

Answers (3)

dhokar.w
dhokar.w

Reputation: 470

If your compiler is configured to compile c code following c98 then you will get this error because following c98 standard the déclaration of variables must be done first then we can make assignment so we can't make declaration of variable in the middle of the code.

However you can select the option to compile your code following the standard c99 and in this case you can make the déclaration of variable in the middle of your code.

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 76508

Change your code to

void f(void) {
  int i;
  int j;
  i = 6;
  j = 20;
}

The problem is that for some old compilers you need to declare the variables before any executable statement. If you do not want to have this problem, switch to a newer compiler.

Upvotes: 0

AndersK
AndersK

Reputation: 36082

In "old" C all declarations must be at the top of the functions. In later versions like C99, C declarations can be anywhere in the code. I guess you have an old compiler.

Upvotes: 4

Related Questions