Wednesday 16 November 2011

Is it valid to use // for comments in a C program? in C programming

Is it valid to use // for comments in a C program?

No. Some C compilers might be able to support the use of //, but that doesn’t make it C. In C, a comment starts with /* and ends with */. C-style comments are still valid in C++, but there’s another convention as well. Everything after (and including) //, up to the end of a line, is considered a comment.
For example, in C you could write this:

i += 1; /* add one to i */
That’s valid C++, but so is the following line:
i += 1; // add one to i
The advantage of the new C++ comments is that you can’t forget to close it, as you can with a C-style
comment:
i += 1; /* add one to i
printf(“Don’t worry, nothing will be “); /* oops */
printf(“lost\n);
In this example, there’s only one comment. It starts on the first line and ends at the end of the second line. The “don’t worry” printf is commented out.

Why is this C++ feature more likely than any other to creep into C compilers? Some compilers use a separate program for a preprocessor. If the same preprocessor is used for C and C++ compilers, there might be a way for the C compiler to get the preprocessor to handle the new C++ comments. C++-style comments are very likely to be adopted into C, eventually. If, one day, you notice that all the C compilers you might use support // comments, feel free to use them in your programs. Until then, use C comments for C code.

Cross Reference:

Introduction to Chapter V: Working with the Preprocessor
V.2: What will the preprocessor do for a program?
XV.1: Should C++ additions to a compiler be used in a C program?

No comments:

Post a Comment