开发者

Strange error with #define in c

I know that #define replaced before the compiling to real values. so why the first code here compile with no error, and the 2nd not?

the 1st;

#include <stdio.h>
#include <stdlib.h>
int main()
{
   printf("bc");
   return 0;
}

the 2nd(not work开发者_Go百科ing);

#include <stdio.h>
#include <stdlib.h>
#define Str "bc";
int main()
{
   printf(Str);
   return 0;
}

error: expected ')' before ';' token

thank you for the answers, and sorry about my poor English...


Because the Str macro evaluates to "bc"; — the semicolon is included. So your macro expands to:

printf("bc";);

You do not need to follow a #define with a semicolon. They end at a newline, rather than at the semicolon like a C statement. It is confusing, I know; the C preprocessor is a strange beast and was invented before people knew better.


Actually the second works and the first doesn't. The problem is the semicolon:

#define Str "bc";
                ^


Use

#define Str "bc"

with your define after the substitution it will look like:

printf("bc";);


The problem with the first one is that Str is replaced with "bc";.

Change it to

#define Str "bc"


You need to remove ; where you define str. Because you will get printf("bc";);


The first code does not compile because you need to remove the semicolon after the #define the 2nd code works as it should.


The first one doesn't work because these lines:

#define Str "bc";
printf(Str);

expand to this line:

printf("bc";);

You want:

#define Str "bc"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜