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.

Walter
  • 44,150
  • 20
  • 113
  • 196
  • 5
    See here http://stackoverflow.com/questions/6713420/c-convert-integer-to-string-at-compile-time. – Dabbler Nov 01 '11 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... – Kerrek SB Nov 01 '11 at 12:22

3 Answers3

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);
iammilind
  • 68,093
  • 33
  • 169
  • 336
2

The 'stringize' preprocessor operator:

#define StaticConverter(V) #V

const char *x = StaticConverter(56);
assert(x[0] == '5' && x[1] == '6' && x[2] == 0);
CapelliC
  • 59,646
  • 5
  • 47
  • 90
0

Use the preprocessor's stringizing operator.

Skizz
  • 69,698
  • 10
  • 71
  • 108