This is an interview question:-
Write a C program which when compiled and run, prints out a message indicating whether the compiler that it is compiled with, allows /* */ comments to nest.
The solution to this problem is given below :-
Sol:- you can have an integer variable nest:
int nest = /*/*/0*/**/1;
if it supports nested comments then the answer is 1 else answ开发者_开发技巧er is 0.
How is this working ? I don't understand the variable declaration.
If the compiler doesn't allow nesting, the first */
will terminate the opening of the multiline comment, meaning the 0
won't be commented out. Written with some spaces:
int nest = /*/*/ 0 * /**/ 1;
resulting in the code
int nest = 0 * 1; // -> 0
If it allows nesting, it will be
int nest = /*/*/0*/**/ 1;
resulting in
int nest = 1;
The short answer to "how is this working" is that:
int nest = /*/*/0*/**/1;
with nested comments becomes something like:
int nest =
// /* (comment level 1)
// /*/ (comment level 2)
// 0
// */*
// */
1;
and without, the extra * makes it:
int nest =
// /*/ (comment level 1)
// */
0
*
// /*
// */
1;
or 0*1
.
Or, I think that's what's happening, but this question is pretty much a disaster. I entirely agree with Blagovest Buyukliev's comment.
int nest = /*/*/0*/**/1;
Nesting not allowed
If nesting is NOT allowed, the first comment's range is:
vvvvv
int nest = /*/*/0*/**/1;
With that comment removed (gap left for readability - the C++ preprocessor substitutes a single space, not sure about C), the next comment seen is:
vvvv
int nest = 0*/**/1;
With that also removed:
int nest = 0* 1;
Nesting allowed
Below, the |+-
line shows the scope of the outer comment, and vvvvvv
indicates teh scope of the inner comment.
+---------+
| |
| vvvvvv |
int nest = /*/*/0*/**/1;
With those comments removed:
int nest = 1;
If it supports nested comments, then you'll have (Stripping the comments):
int nest = 1;
If it does not, then you'll have (Stripping the comments):
int nest = 0 * 1;
That is a big bag of loathsome hurt. My guess is that the third /
possibly cancels the second multi-line comment block, rendering the *
after the zero a multiplication, hence:
/* */0 * /* */ 1 == 0 * 1 == 0 // ==> nested comments aren't supported.
If the compiler understands nested comments, it will just strip the /*/*/0*/**/
part and leave you with the int nest = 1
.
Otherwise, it will see int nest = 0*1
and 0 * 1 == 0
.
精彩评论