By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,194 Members | 884 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,194 IT Pros & Developers. It's quick & easy.

C preprocessor

P: 2
I was told C preprocessor "#define arg1 agr2" would do a text replacement - arg1 string with arg2....

I wrote a few lines of code as follows:

#include "stdio.h"
#define PRNT(v,x) printf("x = %v\n", x)

main() {
int i = 5;
PRNT(d, i);
return 0;
}

I expected that after the preprocessing step, the program would become

main() {
int i = 5;
printf("i = %d\n", i);
return 0;
}

and it should print
i = 5

but the preprocessor #define did not work as expected! - the program printed

i = %v

???? Why does C behave that way? What didn't I understand? Please help
Thanks
EE02IU
P.S. I used Borland C++ 4.52
Oct 2 '06 #1
Share this Question
Share on Google+
1 Reply


Banfa
Expert Mod 5K+
P: 8,916
I was told C preprocessor "#define arg1 agr2" would do a text replacement - arg1 string with arg2....

I wrote a few lines of code as follows:

#include "stdio.h"
#define PRNT(v,x) printf("x = %v\n", x)

main() {
int i = 5;
PRNT(d, i);
return 0;
}
a #defined symbol (PRNT in your case) is used for a text replacement...

except inside strings, the contents of strings are not parsed by the pre-processor for the replacement of #defined symbols

However you can achieve what you want like this

Expand|Select|Wrap|Line Numbers
  1. #define PRNT(v,x)   printf("x = %" #v "\n", x)
  2.  
This makes use of the following 2 features onf the C language

1. Separate strings seperated only by white space are concatinated by the C compiler, for instance

Expand|Select|Wrap|Line Numbers
  1.   printf("H"
  2.       "ell"
  3.       "o Wor"
  4.       "ld\n");
  5.  
outputs

Hello World

This is useful if you have very long strings as you don't have to fit them on one line, or for laying out multiline messages as you can put different output lines on different source lines

2. The preprocessor stringizing token #. #v is iterpreted by the preprocessor as a string containing whatever is in the parameter v
Oct 2 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.