Home > Back-end >  expected a type specifier in C
expected a type specifier in C

Time:03-26

All of my programs before have been working well with C except for today. For some reason I keep getting "expected a type specifier"

I am confused why this is not working.

#include <stdio.h>
printf("Hello World"); // error: expected a type specifer

int test = 90;
printf("%d", test); // same error here: expected a type specifier 
// also getting "variable "test" is not a type name"

CodePudding user response:

You cannot have statements outside of a function in C. That's what is causing the errors you're seeing.

The main function serves at the starting point for a C program, so start by putting the statements in that function.

#include <stdio.h>

int main()
{
    printf("Hello World");

    int test = 90;
    printf("%d", test);

    return 0;
}

CodePudding user response:

You can find the Backus-Naur form for a grammar of the C language in Annex A.2: Phrase structure grammar of the ISO/IEC 9899:1999. There are many other grammars, you can use any of them to parse the code (The annex A.1 presents a grammar for the lexer and the annex A.3 presents a grammar of the preprocessor).

The entry symbol you are interested about is translation-unit.

translation-unit:
    external-declaration
    translation-unit external-declaration

external-declaration:
    function-definition
    declaration

This shows that after the preprocessor converts the pp-lexemes into C-lexemes, one expects the output to contain at the top level either a function-definition or a declaration. Going deeper in the grammar, we see that both function-definition and declaration start with a declaration specifier:

function-definition:
    declaration-specifiers declarator declaration-listopt compound-statement

declaration:
    declaration-specifiers init-declarator-listopt

Hence, your compiler could parse neither of these (function-definition or declaration), as it found a function-call, so it stopped with error: expected a type specifer.

Correctly it would have beed to generate a message like "error: expected a declaration specifer".

But, as I said, there are many grammars of the C language and your compiler may follow another grammar with different symbol names.

  •  Tags:  
  • c
  • Related