Syntax, Semantics, and Conditional Execution

Learn the difference between syntax and semantics with example applications.

Understanding the significance of syntax and semantics

There are many usages of the if statement. When we encounter an if statement in a program, it first checks whether the operation is true or not. If it is true, the code between the if block is executed. Otherwise, program execution continues with the next statement in the program.

The description of the execution part of any if statement is called the semantic definition.

Now, we’ll take a look at two important concepts: syntax and semantics. They’re essential in every programming language.

Here, the rule of natural language follows. Syntax describes the practices in which these words can be combined into sentences. On the other hand, semantics describes what they mean.

Consider a simple example.

Here is my friend, Emilia.

In the sentence above, the syntax and semantics are both flawless. There’s no syntactical error, and the semantic definition is meaningful.

However, what about the following sentence?

Here is my chair, Emilia.

This is also syntactically correct. There’s no syntax error, but is the sentence meaningful? Semantics describes what the sentence means, and this one means nothing. We neither give names to our chairs nor introduce them like this.

In a programming language, syntactical rules are essential, and therefore, we shouldn’t miss a semicolon after an expression in many languages like C++, Java, PHP, etc. Similarly, we shouldn’t use semicolons in Python. That is syntax. We should maintain those rules.

We also can’t use the keywords or reserved words as variable or function names.

Now that syntax is taken care of, what about the semantics?

That’s equally important. If our logical expression is wrong, the program is not meaningful anymore; it takes inputs and gives us an erratic output.

In the code in this lesson, we’ll see how syntax and semantics work together in two different programming languages.

Get hands-on with 1200+ tech skills courses.