Thokchom
Thokchom

Reputation: 1652

Why does /*comment*/ inserted randomly inside C code works in some places only,not everywhere?

Isn't everything between and including /* and */ ignored by the compiler?Isn't it supposed to be so everywhere in a C program, ignored as if it doesn't exist?Why then in my program it works in the most unlikely places,but fails in other places?What is the rule for commenting and what is the reason behind the observation about comments in my following ?program?

#include<stdio.h>
#include<string.h>


int main(void)
{
char str1/*works*/[90];  //comment works
FILE *fp=fopen("D:\\source.txt","r");
if(fp==NULL){p/*Fails*/rintf("ERROR");return 0;}  //comment fails
while(fgets(str1,8/*Fails*/9,fp)!=NULL)  //comment fails
{
    if(strstr(str1,"999.999")==/*Works*/NULL)  //comment works
    printf("%s",str1);
}
fclose/*Works*/(fp);  //comment works

}

Upvotes: 2

Views: 247

Answers (4)

rootFather
rootFather

Reputation: 31

if(fp==NULL){p/*Fails*/rintf("ERROR");return 0;}  //comment fails

Here compiler is treating your code as /p rintf/ due to the fact that comment appears to be a whiltespace so this is the reason your comment fails.

while(fgets(str1,8/*Fails*/9,fp)!=NULL)  //comment fails

Again same mistake, /8 9/ is not valid as interpreted by compiler.

Upvotes: 0

user93353
user93353

Reputation: 14039

C99 says that there is a translation phase which happens prior to the preprocessing. In translation phase3, comments are replaced by space. So obviously your program won't compile. This is given in Section 6.10 of C99.

char str1 [90];  

is valid (space between str1 and [). Hence it compiles.

However

p rintf("ERROR");

isn't valid. Hence it doesn't compile.

Upvotes: 2

Barmar
Barmar

Reputation: 781058

A comment is treated like whitespace by the parser. So when you put it between 8 and 9, you no longer have one number, you have two numbers separated by a space.

Upvotes: 6

nvoigt
nvoigt

Reputation: 77304

It only works in places where you could have inserted whitespace (blanks, tabs, linebreaks).

Upvotes: 15

Related Questions