Question

I was doing the exercise of the K&R2. When i was reading the code by Ben Pfaff in this page http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_1:Exercise_23 I coudn't understand what the single code putchar('/' //*/ 1) mean. While in my compiler, it is a syntax error. So can anyone explain this to me.

Was it helpful?

Solution

If you read the comments at the beginning of the solution it explains why you're seeing that error:

It also contains examples of a comment that ends in a star and a comment preceded by a slash. Note that the latter will break C99 compilers and C89 compilers with // comment extensions.

In a compiler that does not support // style comments, this:

putchar('/' //**/ 
        1) 

Is equivalent to:

putchar('/'/1)

Which is legal -- though odd -- expression (remember that in C a char is a numeric type, so '/'/1 is the same as /). This happens because the sequence /**/ is an empty comment.

In a modern compiler with // style comments, the expression ends up being equivalent to:

puchar('/' 1)

Which is simply an error.

OTHER TIPS

To make it clear, the original code is placed in multiple lines, like so:

    putchar('/' //**/
            1);

From here, /**/ part is a comment, so after pre-processing, the code would look like this:

putchar('/' / 1);

Which is equal to putchar('/');

You are getting compiler error because you are compiling this code either as C99 or, most likely, as C++, where // is a single-line comment. Compile as C89 instead.

Sorry for bad formatting - writing from my phone...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top