Question:medium

Consider the following C code segment: 

a = b + c; 
e = a + 1; 
d = b + c; 
f = d + 1; 
g = e + f; 

In a compiler, this code is represented internally as a Directed Acyclic Graph (DAG). The number of nodes in the DAG is \(\underline{\hspace{2cm}}\).

Show Hint

DAGs eliminate redundant computations by sharing common subexpressions.
Updated On: Jan 30, 2026
Show Solution

Correct Answer: 6

Solution and Explanation

Step 1: Identify common subexpressions.
In the given expression, the subexpression \( b + c \) occurs more than once. When constructing a DAG (Directed Acyclic Graph), such common subexpressions are represented by a single node to avoid redundant computation.

Step 2: Identify distinct operation nodes.
After eliminating redundancy, the distinct arithmetic operations that must be represented are: \[ b + c,\quad a + 1,\quad d + 1,\quad e + f \] Each of these corresponds to one internal (operator) node in the DAG.

Step 3: Identify operand (leaf) nodes.
The operands that appear in the expression and are required as leaves in the DAG are: \[ b,\ c,\ 1 \] (Note that constants such as \(1\) are represented only once, even if reused.)

Step 4: Count total DAG nodes.
- Operand (leaf) nodes: \( b, c, 1 \) → 3 nodes
- Operator (internal) nodes: \( b+c,\ a+1,\ d+1,\ e+f \) → 3 nodes

Therefore, the total number of nodes in the DAG is: \[ 3 + 3 = 6 \]

Final Answer:
\[ \boxed{6} \]

Was this answer helpful?
0