0

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...

3
  • Are you sure the first one is compiling? The error looks like because of the ; after "bc" in your first example. Commented Jul 15, 2011 at 8:15
  • thank you, my mistake, i replace the two code blocks Commented Jul 15, 2011 at 8:17
  • Thank you every body, I forgot the semicolon. Commented Jul 15, 2011 at 8:21

7 Answers 7

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

#define Str "bc";
                ^

Comments

3

Use

#define Str "bc"

with your define after the substitution it will look like:

printf("bc";);

Comments

3

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

Change it to

#define Str "bc"

Comments

2

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

Comments

1

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

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.