The difference between syntax and grammar

grammarprogramming-languagessyntax

I understand the difference between syntax and semantics –

Syntax: how the symbols are combined to form a valid expression or statement.
Semantics: the meaning of those symbols that form an expression or statement.

But what is the grammar? For example: sometimes I hear people say that some construct is "grammatically incorrect but syntactically it is correct". What does it mean?

Best Answer

A grammar is a set of rules that define the syntax for a particular language.

When people are talking specifically about a parser (especially one generated with a parser generator like yacc, Byacc, ANTLR, etc.), they may do a bit more hair-splitting, and talk specifically about those syntactical rules that are encoded using the generator's rules, vs. those parts that are enforced separately by code attached to a rule. For example, in C when you define an array, the size you specify for the array must be strictly positive (not zero). The grammar rule might basically say something like:

typename var_name '[' unsigned_int ']'

...and then separately, there would be a bit of code to check that the unsigned_int was non-zero. In this case, it could make some sense to talk about the requirements of the syntax and the grammar separately from each other, with the two having slightly different requirements (that, enforced together, we presume fit the requirements of the language itself).