96

I've always thought that referring to the syntax of a language was the same as referring to the semantics of a language. But I've been informed that apparently that's not the case. What's the difference?

5

13 Answers 13

110

Semantics ~ Meaning

Syntax ~ Symbolic representation

So two programs written in different languages could do the same thing (semantics) but the symbols used to write the program would be different (syntax).

A compiler will check your syntax for you (compile-time errors), and derive the semantics from the language rules (mapping the syntax to machine instructions say), but won't find all the semantic errors (run-time errors, e.g. calculating the wrong result because the code says add 1 instead of add 2).

5
  • 2
    Error checking is not a criterion for distinguishing between syntax and semantics. A compiler can and must diagnose both syntax errors (like a missing semicolon) and semantic errors (like x + y where there's no appropriate + operator for those operands). Adding 1 rather than 2 is what I'd call a logical error. Oct 13, 2011 at 0:37
  • 3
    @Keith - but logic (as in "logical error") is semantics. Some semantic checks can be done by the compiler - particularly type checking - so I agree that compilers don't only find syntax errors, but Chris only said "won't find all semantic errors", which doesn't imply "can't find any".
    – user8709
    Oct 13, 2011 at 0:42
  • 1
    @Steve314: Agreed. But if you want to make a sharp distinction between errors that a compiler must detect and errors that it needn't detect, then I think "semantic" vs. "logical" is a good way to express that distinction. Oct 13, 2011 at 0:46
  • 4
    @KeithThompson Actually, in theory, a compiler or interpreter for a language with a sufficiently strong and powerful (i.e., dependent) type system can check any arbitrary property of your code (modulo the Halting Problem, if applicable), so breaking semantic errors into "checkable" and "uncheckable" doesn't really make sense in general. Dec 13, 2012 at 20:33
  • @Ptharien'sFlame I'm just going to pull this discussion back out of the clouds for a second by highlighting the 'in theory' part of your statement. In practice, enforcing semantics in code requires additional syntax to give the compilers cues as to the functionality. Additional semantic checking comes as a cost (ie complexity/readability). Stating that a language can be powerful enough to check all semantic errors is like saying a legal system can be perfect enough to prevent all crime. Personally, I prefer freedom over safety but that's what makes this a 'religious' topic. Mar 15, 2013 at 17:06
35

Actually there are not two levels but three:

  • lexical level: how characters are combined to produce language elements ( i and f produces if)
  • syntactical level: how language elements are combined to produce language expressions ( if, (, 42, ==, answer and ) produces a conditional statement)
  • semantic level: how language expressions are converted to CPU instructions in order to form a meaning (a conditional statement allows to execute one branch or the other depending on the result of the boolean expression)
6
  • 10
    A separation between lexing and parsing stages is entirely artificial, it is nothing more than an optimisation. And there are some languages where no finite flat set of lexemes is defined - but still, there is a clearly defined syntax. So, I'd prefer to define lexemes as part of a syntax, is is not a separate entity.
    – SK-logic
    Oct 12, 2011 at 10:39
  • @SK-logic: In many languages, the list of authorised or forbidden lexemes forming a variable name is specified. So the separation makes sense.
    – mouviciel
    Oct 12, 2011 at 11:00
  • 5
    @mouviciel, it make sense as an optimisation only - otherwise you'll just have a ValidIdentifier terminal, which could be defined as something like ![AnyKeyword] [Identifier] (I'm using PEG-like notation here). You don't need a separate lexing pass for such a language. See, for example, GLR-based C++ parsers.
    – SK-logic
    Oct 12, 2011 at 11:48
  • 2
    @EvanPlaice, what are you talking about? My point is that lexing is not necessary (and actually limits your language), not parsing.
    – SK-logic
    Mar 15, 2013 at 17:42
  • 1
    @SK-logic I guess I read your comment to mean the opposite of what you intended. I thought you were talking about cases where only a lexer is needed - like in purely 'regular' or 'context-free' languages. In higher level languages a lexer may not be necessary but it provides a quick way to run a single pass syntax validation. I completely agree that there are many cases where it would be beneficial to turn off or completely eliminate the lexer stage. Mar 15, 2013 at 18:21
23

I will explain it to you with a simple example in the language ENGLISH:

The glass drank Ben

Is a syntactically correct statement. It has a noun, a verb, etc.

But semantically it is wrong, because this statement has no conceivable or correct meaning.

0
15

Semantics describe the logical entities of a programming language and their interactions. Syntax defines how these are expressed in characters.

For example, the concept of pointer arithmetic is part of C's semantics; the way the + and - operators can be used to express pointer operations are part of its syntax.

Sometimes, two languages share part of their semantics, but the syntax differs wildly (e.g. C# and VB.NET - both use value types and reference types, but the characters you type to define them are different); in other cases, two languages are syntactically similar, but the semantics don't match up (consider Java vs. JavaScript, where the similarities often confuse beginners).

2
  • So, "Paradigms" are related with semantics? I mean a paradigm is a set of interrelated semantics?
    – Gulshan
    Oct 12, 2011 at 6:39
  • 1
    @Gulshan, paradigm is a much broader concept than such a formalised thing as semantics. Paradigm may include semantics, but it is more a methodology, or, even broader, a philosophy.
    – SK-logic
    Oct 12, 2011 at 9:01
6

Syntax is how you arrange a language's tokens. Semantics is what those tokens mean (usually, what a particular arrangement of tokens means).

5

You did not specify whether you only refer to programming languages or to general languages used in programming, so my answer is about data languages (such as XML, RDF, data type systems etc.):

Brian L. Meek in his seven golden rules for producing language-independent standards (1995) writes that "one language's syntax can be another's semantics". He refers to the words "syntax" and "semantic" used in data description: so if you stumble upon these words in a specification of some data format, you should better replace both words with "Potrzebie" to make clear that you must work out the meaning for yourself.

The relation between syntax and semantic, at least in exactly specified data, can better be described by the term "encoding". Semantic is encoded in syntax. As recordings can be nested, one language's syntax is another's semantics. If one goes beyond the realm of data, this nesting can be virtually infinite, as described by Umberto Eco as "unlimited semiosis".

To give a an example:

  • XML syntax (the stuff with all these brackets) is syntax with an XML Infoset (an abstract tree) as semantic.
  • An XML Infoset as syntax can express a record in some XML data format as semantic, for instance an RDF/XML document that encodes an RDF graph.
  • An RDF graph (the stuff with URI References) as syntax encodes a graph of abstract resources as semantic.
  • A graph of abstract resources as syntax encodes a conceptual model as semantic.

People usually stop at some level and take it as semantic, but in the end there is no final semantic unless some human being interprets the data in his mind. As soon as one tries to express semantic in form of data, it becomes syntax.

4

If it can be described in BNF (Backus-Naur Form) or something similar, it's syntax. If it can't, it's not.

Semantics, on the other hand, is about the meaning of a program (or other chunk of source code).

And sometimes the line between the two can be blurry.

One way to understand the distinction is to look at the kinds of errors you get when your program's syntax or semantics is incorrect.

A syntax error is a failure of the source code to match the language grammar, for example, not having a semicolon where one is required.

A semantic error is a failure to satisfy other language requirements (what C, for example, calls "constraints"); an example might be writing x + y where x and y are of incompatible types. The language grammar tells you that an addition looks like something + something, but it's not powerful enough to express the requirements on the types of the left and right operands.

(Logical errors, such as using 1 where 2 would be correct, are not generally detectable by the compiler -- though in some cases a compiler can warn about questionable code.)

1

Syntax is grammatical arrangement of words in a sentence i.e. word order.

(English) ‘cat dog boy’ and (programming) ‘hi.5’ is not syntactically correct.

(English) ‘cat hugs boy’ and (programming) ‘*3.2*5*’ is syntactically valid.

Static Semantics is whether syntactically valid statements have any meaning.

(English) ‘I are big’ (programming)(python) ‘3 + ‘hi’’ is syntactically correct but has static semantic error.

Semantics is the meaning associated with syntactically correct string of symbols with no static semantic error i.e. sentence is syntactically and semantically correct, but its meaning may not be what was intended.

(English) ‘Flying planes can be dangerous’ can have two meanings i.e. flying of planes can be dangerous or the planes that are flying can be dangerous.

(Programming) ‘the computer will not generate any error messages, but it will not do what you told it to do; it will do something else.’

Source: MIT 6.00.1

0

Syntax is what the (lexical) symbols say. Semantics is what they mean.

Consider:

C#: condition ? true_value : false_value
VB.NET: If(condition, true_value, false_value)
-- Different syntax, same semantics.

C#: left_value / right_value
VB.NET: left_value / right_value
-- Same syntax, different semantics (for integers).

-2
  1. Syntax refers to formal rules governing the construction of valid statements in a language. Semantics refers to the set of rules which give the meaning of a statement.

  2. Errors due to syntax occur in a program when ruels of the programming language are violated or misused. Errors due to semantics occur in a program when statements are not meaningful.

  3. Word order is the basic principal of syntax, those trying to understand what is written use the syntactic cues of word order to help give the sentence structure and meaning. Semantics are an individuals own interpretation of the meaning of a "sentence" based on their prior knowledge. Therefore a sentence that seemingly makes no syntactic sense, can have meaning when using semantic cues.

  4. Syntax is only concerned with what is linguistically and grammatically correct. Semantics requires all ones prior knowledge which, and is far beyond anything which is language specific.

  5. The sentence "Baby milk drinks" does not have a syntactic meaning, but through semantics most people would interpret it as meaning " Baby drinks milk " as our prior knowledge tells us that a baby drinks milk, and therefore we can find a meaning from the key words.

1
  • 1
    Upvote for everything except last one (point 5)
    – nawfal
    May 22, 2014 at 8:44
-2

Syntax and semantics is like strategy and tactics or left and right.

They are not really independent universal concepts, but a related pair of words that, when you are in a particular context, indicate opposite directions. But the same thing that is strategy on one scale is tactics on another.

So if you are writing code in a language, the syntax is the language you are using and the desired behaviour is the semantics. But if you are implementing, or discussing, the compiler for that language, then the syntax is the grammar and perhaps type system and the semantics everything built on that. And so on.

1
  • 5
    What kind of esoteric BS is that? Like left and right? Like strategy and tactics? Maybe even like Yin and Yang, God and Devil, Harry and Voldemort?
    – JensG
    Feb 8, 2014 at 11:38
-3

Syntax is what the computer understands, semantics is what the human understands.

A compiler/interpreter doesn't care a whit about your design, and in any code compiled down to machine level you'd have a hard time deducing the design. Developers care about design because a good design is about reducing complexity by abstracting complex behaviors and interactions, and different kinds of problems lend themselves to different semantics. The choice of language is largely about how easily and efficiently the semantics you want to use can be expressed in its syntax.

5
  • "Syntax is what the computer understands, semantics is what the human understands" is a great oversimplification. Humans do understand syntax too, and computers understand some kinds of semantics.
    – CesarGon
    Oct 12, 2011 at 12:17
  • 4
    Plainly wrong. There are languages with identical syntax and completely different semantics (e.g., an eager and a lazy versions of a same language), there are languages with virtually no syntax and very rich and variable semantics (e.g., Forth and Lisp). Semantics is how the compiler interprets your language. Human may know nothing about it and still be able to use a language.
    – SK-logic
    Oct 12, 2011 at 12:43
  • @SK-logic, you're contradicting yourself. If different semantics can be expressed with the same syntax, then clearly the semantics are not contained in the syntax, but rather in how it is used. Yet the compiler has only syntax to work with. It doesn't interpret semantics, it interprets syntax. It doesn't compile the same syntax differently based on what the developer meant to say, but only on what he typed. Semantics are supplied by the developer, and are only meaningful to him.
    – kylben
    Oct 12, 2011 at 13:31
  • 3
    @kylben, I am not contradicting myself, because I never said that syntax and semantics are even connected. And compiler is not doing anything with the syntax straight after the parsing stage - compiler is implementing semantics. Clearly your interpretation of terminology is wrong. Read this for a starter: en.wikipedia.org/wiki/Denotational_semantics
    – SK-logic
    Oct 12, 2011 at 14:11
  • 4
    You're talking about a meaning of a program, which is a "semantics" as it would have been defined by a linguist. But in computer science, semantics is a meaning of a language, not a particular program.
    – SK-logic
    Oct 12, 2011 at 14:15
-3

Very short example with "plain c":

void main()
{
  int a = 10;
  int x = a - 1;
  int y = - 1;

  printf("x = %i", x);
  printf("y = %i", y);
    getch();
}

In this example, the syntax for the "-" token is the same, but, it has a different meaning ("semantic), depending where its used.

In the "x" assignament, "-" means the "substraction" operation, In the "y" assignament, "-" means the "negative sign" operation.

4
  • 3
    Incorrect. The two - operators are the same token, but they're syntactically different, because they're used in different contexts. 0 - 1 matches the syntax rule additive-expression: additive-expression - multiplicative-expression, while - 1 matches the syntax rule unary-expression: unary-operator cast-expression (reference: C99 standard). Oct 13, 2011 at 0:30
  • @Keith Thompson: You missed the point. Is a semantics or syntax question, not a C standards question. The standard is right, but, my answer was directed to explain a concept, not, following literally, a standard. It's like a "Captain Kirk" v.s. "Dr Spock" question. Cheers;-)
    – umlcat
    Feb 12, 2014 at 18:36
  • I disagree. The distinction between the two - oeprators is syntactic, not just semantic (though they also have different semantics). Syntax is defined by the language grammar, and the two operators are specified in different sections of the grammar. See the N1570 draft, section 6.5.3 for unary operators and 6.5.6 for additive operators. (BTW, if you're going to use a C example, it should probably be correct; void main() should be int main(void), and you're missing #include <stdio.h> and whatever header declares getch Feb 12, 2014 at 19:05
  • To clarify the point, syntax isn't just about the sequence of tokens, it's about how those tokens build up larger constructs. A compiler typically has a lexical analyzer (tokenizer) and a parser as distinct components; both of them deal with syntax. Feb 12, 2014 at 19:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.