Using the % operator with preprocessor constants

  • Thread starter zahy[dot]bnaya[At]gmail[dot]com
  • Start date
Z

zahy[dot]bnaya[At]gmail[dot]com

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
 
V

Victor Bazarov

zahy[dot]bnaya[At]gmail[dot]com said:
hello,
I have a constant declared as

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

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

const long TABLESIZE = ....
I tried the following code:

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

Substitute the contents of your 'TABLESIZE' macro here. What do you get?
Write it down. Look what the '%' applies to.
printf("%d\n",TABLESIZE);
}



My output is:

172818360
86486400
172972800



How can it be?

Do NOT use macros when you need a constant.

V
 
B

Ben Pope

zahy[dot]bnaya[At]gmail[dot]com said:
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?

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top