user7122079 user7122079 - 13 days ago 6
C Question

C - Turn String into Int on compile

I would like to know if it is possible to turn a known string into a int during the compilation/preprocessing time.

Imagine I have a string with the chars 'AB' and I would like to turn it into a int like in a union:

union StrInt
{
int i;
char c[2];
}


the
c[ ] = 'AB'
will make i have the value 16961

I would like to do the same but during compilation/preprocessing

Answer

Yes. On my architecture (x86_64-pc-linux-gnu ), this:

union {
    int i;
    char c[2];
} u = { .c="AB" };

int main()
{
    printf("%d\n", u.i);
}

prints 16961 just as you expect. (Different implementations may give you different outputs.)

Character arrays may generally be initialized with string literals.

{ .c= { 'A', 'B' } }

would be another way to initalize the c member.