2

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.

4
  • 1
    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. Commented Apr 19, 2011 at 19:44
  • 2
    Some people also use enums to declare constants in C, e.g. enum { N = 100 };. Commented Apr 19, 2011 at 19:53
  • 1
    static is redundant in the C++ example. const objects that are not explicitly declared extern have internal linkage anyway. Commented Apr 19, 2011 at 20:06
  • Yes it was the semicolon. Silly me. Thanks everyone. Commented Apr 19, 2011 at 20:58

3 Answers 3

5

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)
Sign up to request clarification or add additional context in comments.

Comments

3

#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

Comments

1

Another option is to use an enum:

enum {
  X = 5 + 3,
  Y = (X + 10) * 5,
  Z = ((Y + 8) + 0xfff) & ~0xfff
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.