Reputation: 1364
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 working);
#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...
Upvotes: 0
Views: 878
Reputation: 8065
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"
Upvotes: 1
Reputation: 5609
You need to remove ; where you define str. Because you will get printf("bc";);
Upvotes: 2
Reputation: 93010
The problem with the first one is that Str
is replaced with "bc";
.
Change it to
#define Str "bc"
Upvotes: 3
Reputation: 96258
Use
#define Str "bc"
with your define after the substitution it will look like:
printf("bc";);
Upvotes: 3
Reputation: 41374
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.
Upvotes: 4
Reputation: 23268
The first code does not compile because you need to remove the semicolon after the #define the 2nd code works as it should.
Upvotes: 1
Reputation: 182619
Actually the second works and the first doesn't. The problem is the semicolon:
#define Str "bc";
^
Upvotes: 4