Wednesday, 5 December 2012

Worth Read #19

Obscure syntax 

C allows some appalling constructs. Is this construct legal, and if so what does this code do? 

int a = 5, b = 7, c;
c = a+++b;
This question is intended to be a lighthearted end to the quiz, as, believe it or not, this is perfectly legal syntax. The question is how does the compiler treat it? Those poor compiler writers actually debated this issue, and came up with the "maximum munch" rule, which stipulates that the compiler should bite off as big (and legal) a chunk as it can. Hence, this code is treated as:

c = a++ + b;
Thus, after this code is executed, a = 6, b = 7, and c = 12.
If you knew the answer, or guessed correctly, well done. If you didn't know the answer then they wouldn't consider this to be a problem. they find the greatest benefit of this question is that it is good for stimulating questions on coding styles, the value of code reviews, and the benefits of using lint.

Enjoy :)

No comments:

Post a Comment