简体   繁体   中英

Defining constants in C

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 like

static 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 constants 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
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM