CSS Computer Science (Optional) — Paper-I, Section-A, Topic II subtopic. The building blocks that define any programming language.
Core Concepts
- Syntax: the formal rules governing how valid statements are constructed (the grammar of the language). A compiler checks syntax first — a syntax error stops compilation entirely.
- Semantics: the meaning/behavior associated with syntactically valid statements. Code can be syntactically perfect but semantically wrong (logic errors).
- Tokens: the smallest meaningful units the compiler recognizes — every program is broken into tokens before parsing. Categories:
- Keywords: reserved words with fixed meaning (
int, if, return, class) — cannot be redefined or used as identifiers
- Identifiers: programmer-defined names for variables, functions, classes, etc.
- Literals/Constants: fixed values written directly (
42, 3.14, 'x', "text", true)
- Operators: symbols performing operations (arithmetic, relational, logical, bitwise, assignment)
- Punctuators/Separators: symbols that structure code without performing computation (
;, ,, { }, ( ), [ ])
- Comments: non-executable annotations for humans, stripped out before compilation — do not affect semantics at all
Syntax vs Semantics — Example
int x = 5 / 0;
- Syntactically valid — this line parses fine, follows all grammar rules
- Semantically problematic — division by zero is undefined behavior/runtime error, even though the syntax is correct
Contrast with:
int x = 5 0;
- This is a syntax error — missing an operator between
5 and 0; the compiler rejects it before it can even consider meaning
Grammar and Rules
- Every language defines its syntax formally, often using grammar notations like BNF (Backus-Naur Form), which the compiler's parser uses to validate structure
- A statement must be well-formed (follows the grammar) to compile; it must additionally be meaningful in context (e.g. correct types) to behave as intended
💻 Code Examples: C & C++
The syntax-vs-semantics example from above, made runnable, plus tokens labelled:
C:
#include <stdio.h>
int main(void) {
int x = 5 / 2; /* syntactically valid; semantics: integer division -> 2 */
// int y = 5 0; // would be a SYNTAX error -- missing operator, won't compile
printf("%d\n", x); // tokens: printf ( "%d\n" , x ) ;
return 0;
}