Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple Macro not compiling in C 2

Status
Not open for further replies.

mikigcm

Programmer
Oct 24, 2003
3
0
0
CA
Hi,
A macro previously used with Unix C compiler is not compiling with MSDEV. Am I missing something obvious!> Here is the macro:

#define LIMITTO(lwlim, uplim, input1, output1) if (input1 > uplim) { output1 = input1 - (uplim-lwlim); } else if (input1 < lwlim) { output1 = input1 + (uplim-lwlim); } else { output1 = input1; }

using it, for example: LIMITTO(-180.0, 180.0, hset,hset);
causes compiler error C2105: '--' needs l-value


Thanks for your help.
 
> output1 = input1 - (uplim-lwlim); This expands to
[tt]hset = hset - (180.0--180.0)[/tt]

Without extra spaces, it treats the two adjacent minus signs as being the decrement operator (which cannot be applied to a numeric constant since it isn't an l-value)

Fixes
1. Add some spaces to your macro, to ensure that your parameters cannot be joined to tokens within the macro.

2. Better still, add some parentheses
Eg
output1 = (input1) - ( (uplim) - (lwlim) );
--
 
Change lwlim to (lwlim). The macro is expanding (uplim-lwlim) to (180.0--180.0). You actually want (180.0-(-180.0))
 
Thank you guys!

you're abolutely right on.

But, a lingering question...
Why is it that this worked on a unix C-compiler (as is). Are there compiler options to set?

just curious. In the meantime, I can modify all these macros manually.
 
Strange - which flavour of Unix was this. Doesn't work on my copy of gcc.
 
This is almost certainly a difference is the tokenising rules between a pre-ANSI compiler (Unix cc) and an ANSI compiler (MSDEV).

Code:
a--b
Is ambiguous without any additional spaces or parentheses, it could mean any of these

Code:
a-- b
Code:
a- -b
Code:
a --b

Since the Unix C compiler did the right thing (either by design or by bug), the original author of the code thought nothing more of it (it works, move on). It's only later when you come along to port the code that this subtle problem raises its head.

Porting code is full of all sorts of surprises like this.

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top