Take the 2-minute tour ×

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.

share|improve this question
People have already given the solution - but I just want to point out the reason why you need to remove the semicolon. #define in c causes the preprocessor to do a textual substitution before compilation, so imagine taking the contents of X and plugging it into Y and you will likely see what the problem is. –  Gavin H Apr 19 '11 at 19:44
Some people also use enums to declare constants in C, e.g. enum { N = 100 };. –  Pascal Cuoq Apr 19 '11 at 19:53
static is redundant in the C++ example. const objects that are not explicitly declared extern have internal linkage anyway. –  Charles Bailey Apr 19 '11 at 20:06
Yes it was the semicolon. Silly me. Thanks everyone. –  riderchap Apr 19 '11 at 20:58
add comment

3 Answers

up vote 5 down vote accepted

You need to remove the semi-colon from the #define X line

#define X (5+3)
share|improve this answer
add comment

#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()

will result in evaluating very_heavy_calc() twice

share|improve this answer
add comment

Another option is to use an enum:

enum {
  X = 5 + 3,
  Y = (X + 10) * 5,
share|improve this answer
add comment

Your Answer


