Tuesday, 8 January 2013

C/C++ Puzzles: PART - 17

Rule of 'Maximal Munch'

  This rule is also called the 'Greedy Technique', which is used by the lexical analyzer of a C/C++ Compiler. This rule tells us how to evaluate tokens in C/C++. For example consider the following statement.

int x=20, y=10, z;
z=x--y;


What is the Output? One possible Output is obtained by considering the statement as z = x-  -y; In that case the Output is 30. But if you compile the code, you will get a syntax error. The rule of 'Maximal Munch' has played a role here. C/C++ lexical analyzer always identifies the largest possible token from a given statement. So the above statement is read by the lexical analyzer as z=x--  y; So instead of recognizing the Minus operator (-) followed by the Unary Minus operator (-), a Unary Decrement operator (--) is recognized by the C/C++ lexical analyzer. Thus the statement shows a syntax error because of the missing semicolon after the Unary Decrement operator.

Now Consider the following Statements.

//1
x=20;
y=10;
z=x++y;
printf("\n%d", z);

//2
x=20;
y=10;
z=x+++y;
printf("\n%d", z); 

//3
x=20;
y=10;
z=x++++y;
printf("\n%d", z);

//4
x=20;
y=10;
z=x+++++y;
printf("\n%d", z);  
 
Which of them works and which of them shows an error ?
If you didn't get the answer, please select the red text area given below using your mouse to view the answer.

1. z=x++y; Shows a Syntax Error because it is taken as 
z=x++  y; by the Compiler.
2. z=x+++y; Shows the Output as 30 because it is taken as 
z=x++  +y; by the Compiler.
3. z=x++++y; Shows a Syntax Error because it is taken as 
z=x++   ++y; by the Compiler.
4. z=x+++++y; Shows a Syntax Error because it is taken as 
z=x++  ++  +y; by the Compiler.        
 

No comments:

Post a Comment