Exemple concret
Tokenisation
Tokens : int, a, =, 5, +, 3, *, 2, ;
AST Mermaid
graph TD
A["="] --> B["a : int"]
A --> C["+"]
C --> D["5 : int"]
C --> E["*"]
E --> F["3 : int"]
E --> G["2 : int"]
Interprétation :
- Racine : affectation
= - Branche gauche : variable
a - Branche droite :
5 + (3 * 2)
Priorité respectée : multiplication avant addition.
Exemple 1.1 : 5 + 3
Tokenisation
[5] [+] [3]
AST Mermaid
graph TD
A["+ : int"] --> B["5 : int"]
A --> C["3 : int"]
Exemple 2.1 : 5 + 3.0
Tokenisation
[5] [+] [3.0]
AST avec conversion
graph TD
A["+ : float"] --> B["Cast(float ← 5:int)"]
B --> C["5 : int"]
A --> D["3.0 : float"]
Règle de promotion : int + float → float
Exercice 2.2 : divisions en C
| Expression | Type d’opération | Résultat |
|---|---|---|
7 / 2 |
division entière | 3 |
7.0 / 2.0 |
division flottante | 3.5 |
7 / 2.0 |
promotion en float | 3.5 |
Exercice 3.5 : Incrémentation
Post-incrément :
y = x++;
graph TD
A["="] --> B["y"]
A --> C["Post++"]
C --> D["x"]
Sens d’exécution :
- Lire
x(5) - Retourner l’ancienne valeur
- Incrémenter
xà 6
Pré-incrément :
y = ++x;
graph TD
A["="] --> B["y"]
A --> C["Pre++"]
C --> D["x"]
Sens d’exécution :
- Incrémenter
x→ 6 - Lire la nouvelle valeur pour l’assignation
Exercice 4.3 – Macros et risques
Mauvaise macro
#define DOUBLE(x) x * 2
int result = DOUBLE(3 + 1);
AST Mermaid
graph TD
A["*"] --> B["+"]
B --> C["3"]
B --> D["1"]
A --> E["2"]
Évaluation incorrecte :
3 + (1 * 2) = 5
Bonne macro
#define DOUBLE(x) (x) * 2
int result = DOUBLE(3 + 1);
AST Mermaid
graph TD
A["*"] --> B["( + )"]
B --> C["3"]
B --> D["1"]
A --> E["2"]
Tâche maison : comparer deux expressions
Expression 1 :
int x = 2 + 3 * 4;
graph TD
A["="] --> B["x"]
A --> C["+"]
C --> D["2"]
C --> E["*"]
E --> F["3"]
E --> G["4"]
Expression 2 :
int y = (2 + 3) * 4;
graph TD
A["="] --> B["y"]
A --> C["*"]
C --> D["+"]
D --> E["2"]
D --> F["3"]
C --> G["4"]