0

I have an integer constant known at compile time (but not at code-writing time) and I would like to generate, also at compile time, a const char* holding them as ASCII. For example

const int  C         = IntegerConst;
const char*C_as_text = StaticConvert(A);

such that if IntegerConst is given in some #included header file, say IntegerConst=42, than C_as_text="42".

Any idea how to get such a StaticConvert() functionality? In principle this must be possible, as the compiler and preprocessor have all the necessary information at hand.

2
  • 5
    See here stackoverflow.com/questions/6713420/…. Commented Nov 1, 2011 at 11:52
  • If the number is itself a constant expression that's the result of some computation (maybe sizeof(MyType)?), we could discuss a template solution... Commented Nov 1, 2011 at 12:22

3 Answers 3

3

You can use preprocessor directive:

#define StaticConvert(N) #N

Here the condition is that you need to provide the number itself as N. e.g.

const int C = 42;
const char *C_as_test = StaticConvert(42);
Sign up to request clarification or add additional context in comments.

1 Comment

well, this will not do in my case, since C is not a literal.
2

The 'stringize' preprocessor operator:

#define StaticConverter(V) #V

const char *x = StaticConverter(56);
assert(x[0] == '5' && x[1] == '6' && x[2] == 0);

Comments

0

Use the preprocessor's stringizing operator.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.