#define problem

OP #1645965
Rate this post
• ▲ useful
▼ not useful
Say I define this:

#define MENU(A, B, C, D) lcd_DspStr("A  \x29  B  \x29  C  \x29  D")

Then do this in my program:

MENU(\x30, \x30, \x30, \x30);

lcd_DspStr() is a function I wrote to write to my LCD and it works fine 
when placing text straight into the quotes.  In this case, I'm using a 
special font that contains symbols, rather than ASCII characters, so 
that's why I'm using "\x30" or similar.  It works perfect if I forget 
about using the #define.

Anyway, I would expect this setup to work, if it replaced A with \x30 
and so on.  But it doesn't.  It compiles fine, but I get weird results 
so the define is obviously not doing what I thought it would.  Where am 
I going wrong?
Guest #1645978
Rate this post
• ▲ useful
▼ not useful
> Anyway, I would expect this setup to work, if it replaced A with \x30
> and so on.  But it doesn't.  It compiles fine, but I get weird results
> so the define is obviously not doing what I thought it would.  Where am
> I going wrong?

#define doesn't replace anything within a string.

Try:

#define MENU(A, B, C, D) lcd_DspStr(#A "  \x29  " #B "  \x29  " #C " 
\x29  " #D)

Then do this in my program:

MENU(\x30, \x30, \x30, \x30);
Guest #1646560
Rate this post
• ▲ useful
▼ not useful
And the other thing Rolf used, is the fact that the compiler has to 
catanate strings on its own if they aray not seperated by some other 
character then whitespace

   "Hello" " World"

is identical to "Hello World"

So he first used the stringize operator in
1
#define MENU(A, B, C, D) lcd_DspStr(#A "  \x29  " #B "  \x29  " #C " \x29  " #D)

with a macro call of
1
  MENU(\x30, \x30, \x30, \x30);

to first have A, B, C, D replaced with the given macro arguments, where 
each argument is enclosed in quotes (by the stringize operator), which 
gives
1
  lcd_DspStr("\x30" "  \x29  " "\x30" "  \x29  " "\x30" " \x29  " "\x30")

which in turn is string-catanated by the compiler to become
1
  lcd_DspStr("\x30  \x29  \x30  \x29  \x30 \x29  \x30")

... the intendet result.

Reply

A question of your own? This thread is over 16 years old. Ask it in a thread of its own – more people read along there, and it gets answered more often and sooner.

Start a new thread

A fix, an addition or feedback on this thread? Then reply here.

Formatting
  • [c]C-Code[/c]
  • [code]code in other languages, ASCII drawings[/code]
  • [math]formula (LaTeX syntax)[/math]
  • [[Title]] – link to an article
  • Link to another post: right-click its post ID (#8078628), copy the address, paste it into the text

More about formatting

Post long source code as an attachment, not in the text.

Already registered? Log in

Not shown to anyone. We send you a link; your post appears once you confirm it there.

By submitting you create a free account and accept the terms of use.