This one bit me today

Tom Karzes karzes at mfci.UUCP
Thu Oct 12 15:31:01 AEST 1989


In article <267 at wsl.UUCP> john at wsl.UUCP (John Allen on wsl) writes:
>The /* construct for start of comment is not in the 'C' compiler but in the 
>preprocessor.

I don't believe that's part of the language definition.  Traditionally,
however, comment recognition exists in BOTH the C preprocessor and the
compiler.  On most Unix systems with pcc-derived compilers, cpp will, by
default, strip comments, but has a -C switch which will cause it to pass
them through, in which case the compiler will ignore them.

By taking advantage of the fact that cpp won't back up past the point of
a macro expansion, and the fact that the beginning of a comment is indicated
by a pair of characters, it is possible to sneak comments through cpp even
with the default behavior of stripping comments.

For example:

    % cat cic.c
    /* This is a comment which cpp will catch */

    #define X()*

    /X() This is a comment which will sneak by cpp */

    main()
    {
        printf("No syntax error.\n");
    }
    %

If this is run through cpp, the first comment is stripped and the second
is "introduced":

    % /lib/cpp cic.c
    # 1 "cic.c"




    /* This is a comment which will sneak by cpp */

    main()
    {
        printf("No syntax error.\n");
    }
    %

As you can see, the compiler will ignore this comment:

    % cc cic.c -o cic
    % cic
    No syntax error.
    %

Finally, if the -C switch is passed to cpp, both comments are retained:

    % /lib/cpp -C cic.c
    # 1 "cic.c"
    /* This is a comment which cpp will catch */



    /* This is a comment which will sneak by cpp */

    main()
    {
        printf("No syntax error.\n");
    }
    %



More information about the Comp.lang.c mailing list