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
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