I was working with C++ for a long time and now I am on a C project.
I am in the process of converting a C++ program to C.I am having difficulty with the constants used in the program.
In the C++ code we have constants defined likestatic const int X = 5 + 3;
static const int Y = (X + 10) * 5
static const int Z = ((Y + 8) + 0xfff) & ~0xfff
In C, these definitions throw error. When I use #defines instead of the cons开发者_如何转开发tants like
#define X (5+3);
#define Y (((X) + 10) * 5)
#define Z ((((Y) + 8) + 0xfff) & ~0xfff)
the C compiler complains about the definitions of "Y" and "Z".
Could anyone please help me to find a solution for this.
You need to remove the semi-colon from the #define X line
#define X (5+3)
#define Y (((X) + 10) * 5)
#define Z ((((Y) + 8) + 0xfff) & ~0xfff)
#define X (5+3);
is wrong, it needs to be #define X (5+3)
(without ';')
also be aware of the difference between using static const and #define: in static const, the value is actually evaluated, in #define, it's pre-processor command, so
#define n very_heavy_calc()
...
n*n;
will result in evaluating very_heavy_calc() twice
Another option is to use an enum:
enum {
X = 5 + 3,
Y = (X + 10) * 5,
Z = ((Y + 8) + 0xfff) & ~0xfff
};
精彩评论