preprocessor bug?

G

Gilles

Hi,

I'm trying to find a automated way of defining a macro, depending on another macro's value. More precisely, I try to define for "BAR" the larger power of 2 strictly smaller than "FOO", up to 2048.

Here is my sample code:

-------------8<--------------------------------------------------
#include <stdio.h>

#if FOO > 1024
#define BAR 1024
#elif FOO > 512
#define BAR 512
#elif F00 > 256
#define BAR 256
#elif FOO > 128
#define BAR 128
#elif FOO > 64
#define BAR 64
#elif F00 > 32
#define BAR 32
#elif FOO > 16
#define BAR 16
#elif FOO > 8
#define BAR 8
#elif FOO > 4
#define BAR 4
#elif FOO > 2
#define BAR 2
#else
#define BAR 1
#endif

int main(int argc, char *argv[]) {
printf("FOO: %d BAR: %d\n", FOO, BAR);
return 0;
}
-------------8<--------------------------------------------------

The code, albeit not especially pretty, does look quite straightforward to me. However, when I try it, I get strange results:

gilles@localhost:~/tmp$ gcc -DFOO=513 foo.c && ./a.out
FOO: 513 BAR: 512
gilles@localhost:~/tmp$ gcc -DFOO=512 foo.c && ./a.out
FOO: 512 BAR: 128

The first line is what I expected, but the second is not! This should have given 256 for BAR.
Do I miss something obvious or is that a preprocessor bug?

Just for information, system is Ubuntu 12.04 and gcc version is 4.6.3.

Thanks for any help.

Gilles
 
G

Gilles

Gilles said:
I try to define for "BAR" the larger power of 2 strictly smaller than "FOO", up to 2048. [snip]
Do I miss something obvious or is that a preprocessor bug?

You missed something very obvious indeed - prepare to kick yourself!

Your code says
#elif FOO > 512
#define BAR 512

And 512 is /not/ greater than 512...

Yes, 512 is not greater than 512, so I expect BAR to be 256. But I get 128, hence my posting here.
 
J

Joe Pfeiffer

Gilles said:
Hi,

I'm trying to find a automated way of defining a macro, depending on another macro's value. More precisely, I try to define for "BAR" the larger power of 2 strictly smaller than "FOO", up to 2048.

Here is my sample code:

-------------8<--------------------------------------------------
#include <stdio.h>

#if FOO > 1024
#define BAR 1024
#elif FOO > 512
#define BAR 512
#elif F00 > 256
#define BAR 256
#elif FOO > 128
#define BAR 128

You compare FOO (that's eff oh oh) against 512, but F00 (that's eff zero
zero) against 256.
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top