146

What is the difference between syntax and semantics in programming languages (like C, C++)?

haccks
  • 97,141
  • 23
  • 153
  • 244

10 Answers10

228

Syntax is about the structure or the grammar of the language. It answers the question: how do I construct a valid sentence? All languages, even English and other human (aka "natural") languages have grammars, that is, rules that define whether or not the sentence is properly constructed.

Here are some C language syntax rules:

  • separate statements with a semi-colon
  • enclose the conditional expression of an IF statement inside parentheses
  • group multiple statements into a single statement by enclosing in curly braces
  • data types and variables must be declared before the first executable statement (this feature has been dropped in C99. C99 and latter allow mixed type declarations.)

Semantics is about the meaning of the sentence. It answers the questions: is this sentence valid? If so, what does the sentence mean? For example:

x++;                  // increment
foo(xyz, --b, &qrs);  // call foo

are syntactically valid C statements. But what do they mean? Is it even valid to attempt to transform these statements into an executable sequence of instructions? These questions are at the heart of semantics.

Consider the ++ operator in the first statement. First of all, is it even valid to attempt this?

  • If x is a float data type, this statement has no meaning (according to the C language rules) and thus it is an error even though the statement is syntactically correct.
  • If x is a pointer to some data type, the meaning of the statement is to "add sizeof(some data type) to the value at address x and store the result into the location at address x".
  • If x is a scalar, the meaning of the statement is "add one to the value at address x and store the result into the location at address x".

Finally, note that some semantics cannot be determined at compile-time and must therefore must be evaluated at run-time. In the ++ operator example, if x is already at the maximum value for its data type, what happens when you try to add 1 to it? Another example: what happens if your program attempts to dereference a pointer whose value is NULL?

In summary, syntax is the concept that concerns itself only whether or not the sentence is valid for the grammar of the language . Semantics is about whether or not the sentence has a valid meaning.

haccks
  • 97,141
  • 23
  • 153
  • 244
Jeff N
  • 2,789
  • 1
  • 9
  • 4
  • OK. If `x` is at the maximum value for its data and `1` is added to it then it results in some weird output (`0`), isn't it semantic error? – haccks Jul 29 '13 at 19:09
  • Consider an odometer in a vehicle -- it has a series of interrelated wheels with the digits 0 through 9 printed on each one. The rightmost wheel rotates the fastest; when it wraps from 9 back to zero, the wheel to its immediate left advances by one. When this wheel advances from 9 to 0, the one to its left advances, and so on. – Jeff N Jul 29 '13 at 19:20
  • A datatype is like the wheel of an odometer: it can only hold up to a certain value. When the maximum value is reached, the next advance causes the wheel to return to zero. Whether or not this is a semantic error depends on the language rules. In this case, you need to refer back to the C language standard. I don't know exactly what the C language standard says, but here are some of the options. Overflow is: -not an error; the result is zero. -an error; the compiler MUST generate an overflow exception. -UNDEFINED;the compiler is free to do whatever it wants. – Jeff N Jul 29 '13 at 19:32
  • 2
    In case anybody cares about the specific example, unsigned overflow is defined as modular arithmetic (so `UINT_MAX + 1 == 0`). Signed overflow is undefined. Modern compilers *usually* have `INT_MAX + 1 == INT_MIN`, but there are cases you can't count on this (e.g. `for (i = 0; i <= N; ++i) { ... }` where `N` is `INT_MAX` is not infinite depending on optimization; see http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html). – Daniel H Mar 04 '14 at 06:07
  • "note that some semantics cannot be determined at compile-time and must therefore must be evaluated at run-time" - I like how this has a parallel to natural languages. You can't know the meaning of some phrases without context. For example, in the phrase "He likes bananas" the meaning of "he" depends on context. – ymln Dec 20 '18 at 21:20
31

Syntax refers to the structure of a language, tracing its etymology to how things are put together.
For example you might require the code to be put together by declaring a type then a name and then a semicolon, to be syntactically correct.

Type token;

On the other hand, the semantics is about meaning. A compiler or interpreter could complain about syntax errors. Your co-workers will complain about semantics.

doctorlove
  • 17,477
  • 2
  • 41
  • 57
  • 1
    @Talespin_Kit meaning rather than structure: logic is more an abstraction e.g. P => Q, etc or !!P = P, but when you add semantics things can have subtlety, if P is "happy", then !!P is "I'm not un-happy" != "I'm happy" – doctorlove Nov 21 '14 at 09:34
  • 14
    +1 for "A compiler or interpreter could complain about syntax errors. Your co-workers will complain about semantics." – GeekyJ Dec 31 '15 at 12:25
12

Wikipedia has the answer. Read syntax (programming languages) & semantics (computer science) wikipages.

Or think about the work of any compiler or interpreter. The first step is lexical analysis where tokens are generated by dividing string into lexemes then parsing, which build some abstract syntax tree (which is a representation of syntax). The next steps involves transforming or evaluating these AST (semantics).

Also, observe that if you defined a variant of C where every keyword was transformed into its French equivalent (so if becoming si, do becoming faire, else becoming sinon etc etc...) you would definitely change the syntax of your language, but you won't change much the semantics: programming in that French-C won't be easier!

Basile Starynkevitch
  • 1
  • 16
  • 251
  • 479
9

Semantics is what your code means--what you might describe in pseudo-code. Syntax is the actual structure--everything from variable names to semi-colons.

thumbtackthief
  • 5,585
  • 6
  • 36
  • 72
  • Is it a conversation between different people ? Or is it just one post ? I don't get it. E.g "No idea what the following is supposed to mean. It couldn't be more wrong". – doubleOrt Jun 20 '18 at 13:57
7
  • You need correct syntax to compile.
  • You need correct semantics to make it work.
meaning-matters
  • 18,141
  • 8
  • 65
  • 115
5

Syntax is the structure or form of expressions, statements, and program units but Semantics is the meaning of those expressions, statements, and program units. Semantics follow directly from syntax. Syntax refers to the structure/form of the code that a specific programming language specifies but Semantics deal with the meaning assigned to the symbols, characters and words.

Kobina Ebo
  • 51
  • 1
  • 1
2

Understanding how the compiler sees the code

Usually, syntax and semantics analysis of the code is done in the 'frontend' part of the compiler.

  • Syntax: Compiler generates tokens for each keyword and symbols: the token contains the information- type of keyword and its location in the code. Using these tokens, an AST(short for Abstract Syntax Tree) is created and analysed. What compiler actually checks here is whether the code is lexically meaningful i.e. does the 'sequence of keywords' comply with the language rules? As suggested in previous answers, you can see it as the grammar of the language(not the sense/meaning of the code). Side note: Syntax errors are reported in this phase.(returns tokens with the error type to the system)

  • Semantics: Now, the compiler will check whether your code operations 'makes sense'. e.g. If the language supports Type Inference, sematic error will be reported if you're trying to assign a string to a float. OR declaring the same variable twice. These are errors that are 'grammatically'/ syntaxially correct, but makes no sense during the operation. Side note: For checking whether the same variable is declared twice, compiler manages a symbol table

So, the output of these 2 frontend phases is an annotated AST(with data types) and symbol table.

Understanding it in a less technical way

Considering the normal language we use; here, English:

e.g. He go to the school. - Incorrect grammar/syntax, though he wanted to convey a correct sense/semantic.

e.g. He goes to the cold. - cold is an adjective. In English, we might say this doesn't comply with grammar, but it actually is the closest example to incorrect semantic with correct syntax I could think of.

  • [Compilers](https://medium.com/hackernoon/compilers-and-interpreters-3e354a2e41cf#:~:text=Compiler%20vs.&text=The%20main%20difference%20is%20that,representation%20and%20immediately%20evaluate%20it.) This link might be helpful to learn more – Vedant Panchal Jun 19 '20 at 14:19
  • what about interpreted languages? – hack3r_0m Feb 13 '21 at 09:04
  • 1
    A good question! But I don't think I can answer that. In my mind, basically, the same language can be either interpreted or compiled, based on the tool (realtime/interactive or compiler). Still, in the traditional sense, the answer helps to give an idea about any form of language. – Vedant Panchal Feb 13 '21 at 10:08
2

He drinks rice (wrong semantic- meaningless, right syntax- grammar)

Hi drink water (right semantic- has meaning, wrong syntax- grammar)

  • Welcome to Stack Overflow. Before answering an old question having an accepted answer (look for green ✓) as well as other answers ensure your answer adds something new or is otherwise helpful in relation to them. Here is a guide on [How to Answer](http://stackoverflow.com/help/how-to-answer). – help-info.de Sep 05 '20 at 17:26
1

Syntax: It is referring to grammatically structure of the language.. If you are writing the c language . You have to very care to use of data types, tokens [ it can be literal or symbol like "printf()". It has 3 tokes, "printf, (, )" ]. In the same way, you have to very careful, how you use function, function syntax, function declaration, definition, initialization and calling of it.

While semantics, It concern to logic or concept of sentence or statements. If you saying or writing something out of concept or logic, then you are semantically wrong.

Blade
  • 554
  • 7
  • 24
Hafiz Shehbaz Ali
  • 2,306
  • 21
  • 20
1

The syntax of a programming language is the form of its expressions, statements, and program units. Its semantics is the meaning of those expressions, statements, and program units. For example, the syntax of a Java while statement is

while (boolean_expr) statement

The semantics of this statement form is that when the current value of the Boolean expression is true, the embedded statement is executed. Then control implicitly returns to the Boolean expression to repeat the process. If the Boolean expression is false, control transfers to the statement following the while construct.

BoraKurucu
  • 109
  • 6