Syntax and semantics are concepts that apply to all languages, including programming languages. Programming languages are considered artificial languages, just like natural languages such as English and Mandarin.
Syntax of a Language
- The syntax of a language refers to a set of characters and their acceptable arrangements or sequences.
- In English, for example, the syntax includes the alphabet, punctuation, properly spelled words, and properly punctuated sentences.
- A syntactically correct sentence in English would be: “Hello there, how are you?” An example of a sentence that is not syntactically correct is: “Hello there, hao are you?”
- In this sentence, the sequence of letters “hao” is not a valid word in the English language.
- In Mandarin, the term “Hao” is syntactically correct and translates to “good.”
- Thus, each language has its own syntax and semantics, which define the structure and meaning of the language.
Semantics of a Language
- The semantics of a language deals with the meaning associated with each syntactically correct sequence of characters.
- Semantics determine the interpretation and understanding of language constructs.
- A sentence can be syntactically correct but semantically incorrect, rendering it meaningless.
- For instance, the sentence “Colourless green ideas sleep furiously” is syntactically correct but semantically incorrect, and thus has no meaning.
Program Translation
- The Central Processing Unit (CPU) is designed to interpret and execute a specific set of instructions represented in binary form (i.e., 1s and 0s) called machine code.
- Only programs in machine code can be executed by a CPU.
- Writing programs in machine code is tedious and error prone. Most programs are written in high-level programming languages (e.g., Python)
- Since
high-level programs are not in machine code, they require translation.
- A translator program is
necessary to convert high-level language programs into machine code, as
CPUs can only execute instructions in machine code.
- There are two fundamental types of translators: Complier and Translator
Compiler:
- A compiler translates programs directly into machine code.
- Programs can then be executed by the CPU.
- Compiled programs generally execute faster than interpreted on.
Interpreter:
- An interpreter executes program instructions directly, “running on top of” the CPU.
- It translates and executes instructions immediately as they are entered. This is referred to as interactive mode.
- Python is an example of a language executed by an interpreter.