• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

126
Views
Why does C's BNF grammar allow declarations with an empty sequence of init-declarators?

When looking through C's BNF grammar, I thought it was weird that the production rule for a declaration looked like this (according to https://cs.wmich.edu/~gupta/teaching/cs4850/sumII06/The%20syntax%20of%20C%20in%20Backus-Naur%20form.htm):

<declaration> ::=  {<declaration-specifier>}+ {<init-declarator>}* ;

Why use an * quantifier (meaning zero or more occurrences) for the init-declarator? This allows statements such as int; or void; to be syntactically valid, even though they're semantically invalid. Couldn't they have just used a + quantifier (one or more occurrences) instead of * in the production rule?

I tried compiling a simple program to see what the compiler outputs and all it does is issue a warning.

Input:

int main(void) {
    int;
}

Output:

test.c: In function ‘main’:
test.c:2:5: warning: useless type name in empty declaration
     int;
     ^~~
over 3 years ago · Santiago Trujillo
2 answers
Answer question

0

declaration-specifier includes type-specifier, which includes enum-specifier. A construct like

enum stuff {x, y};

is a valid declaration with no init-declarator.

Constructs like int; are ruled out by constraints beyond the grammar:

A declaration other than a static_assert declaration shall declare at least a declarator (other than the parameters of a function or the members of a structure or union), a tag, or the members of an enumeration.

I would guess that there are backward compatibility reasons behind your compiler only issuing a warning.

over 3 years ago · Santiago Trujillo Report

0

A declaration without an init declarator:

<declaration> ::=  {<declaration-specifier>}+ {<init-declarator>}* ;

is harmless for declaration specifier lists that aren't a single enum/struct/union specifier and it usefully matches those that are.

In any case, the presented grammar will also erroneously match declarations like int struct foo x; or double _Bool y; (it allows multiple specifiers in order to match things like long long int), but all these can be detected later, in a semantic check.

The BNF grammar itself won't weed out all illegal constructs.

over 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error