0

I was looking at the C grammer on K&R and i found this:

compound-statement:
{ declaration-list opt statement-list opt }

declaration-list:
declaration
declaration-list declaration

statement-list:
statement
statement-list statement

Which means that we can't have declarations after statements. However i am doing this really often like:

#include <stdio.h>

int main()
{
  printf("Lets use a new block");
  {
    int a=1;
    printf("%d",a);
    int b=3;
    printf("%d",b);
  }
  return 0;
}

This code compiles with no warning and no errors. Am i not understanding the grammar correctly?

user1478167
  • 83
  • 11

2 Answers2

4

To get the error you want, pass these flags to gcc:

-std=c90 -pedantic-errors

GNU extensions, as well as more recent C standards, allow declarations after other statements in a scope.

hyde
  • 60,639
  • 21
  • 115
  • 176
3

You understand the grammar fine. However, C has advanced since the K&R days and now the grammar accepts interleaved declarations and statements.

rici
  • 234,347
  • 28
  • 237
  • 341