Using the % operator with preprocessor constants

Using the % operator with preprocessor constants

Post by zahy[dot]b » Thu, 09 Mar 2006 23:30:20


hello,
I have a constant declared as

#define TABLESIZE 16*15*14*13*12*11*10*9/3 /// 172972800

I tried the following code:

if (TABLESIZE == 172972800)
{
printf("%d\n",518763960%172972800);
printf("%d\n",518763960%TABLESIZE);
printf("%d\n",TABLESIZE);
}



My output is:

172818360
86486400
172972800



How can it be?
Thanks
 
 
 

Using the % operator with preprocessor constants

Post by Victor Baz » Thu, 09 Mar 2006 23:38:45


It's not a constant. It's a piece of text. If you need a constant, use

const long TABLESIZE = ....


Substitute the contents of your 'TABLESIZE' macro here. What do you get?
Write it down. Look what the '%' applies to.


Do NOT use macros when you need a constant.

V
--
Please remove capital As from my address when replying by mail

 
 
 

Using the % operator with preprocessor constants

Post by Ben Pop » Thu, 09 Mar 2006 23:46:14


Macros are evil.

Rule 1* is to always put it in brackets:
#define TABLESIZE (16*15*14*13*12*11*10*9/3)

Macros are text replacement so your second printf expands to:

printf("%d\n",518763960%16*15*14*13*12*11*10*9/3);

Rule one comes after at least 3 other rules, which essentially all say:
Don't use macros!

Ben Pope
--
I'm not just a number. To many, I'm known as a string...