Brandon
Brandon

Reputation: 23485

When is a multi-character constant useful?

In Microsoft Detours Library, they do: const ULONG DETOUR_REGION_SIGNATURE = 'Rrtd';

I'm trying to figure out exactly WHY they do this. When I print it on my system it prints: 1383232612

which is the same as: (0x52 << 24) | (0x72 << 16) | (0x74 << 8) | 0x64 or ('R' << 24) + ('r' << 16) + ('t' << 8) + 'd'

Why do they do this? I read it's not portable and depends entirely on the endianness of the system and it gives warnings when compiling with GCC and Clang..

Upvotes: 4

Views: 186

Answers (1)

eerorika
eerorika

Reputation: 238421

When is a multi-character constant useful?

When you want some arbitrary constant integer value that looks like text when interpreted as a sequence of characters. This apparent "textuality" is occasionally useful for the programmer to quickly recognise the constant from binary soup.

For example, let's consider a binary protocol or file format that contains a message. Let's say there are N possible messages including "configure", "push" and "plop". We can encode the message as an integer. enum is useful here:

enum message {
    CONFIGURE,
    PUSH,
    PLOP,
    ...
};

Now, when the programmer observes such file in a hex editor, it will show all of those messages as .... in text because those bytes do not represent a printable character, or possibly 02 00 in hex. Why does 02 00 mean "plop"? There is no connection.

Instead, we could give those four bytes values that do have meaningful representation as text:

enum message {
    CONFIGURE = 'CONF',
    PUSH      = 'PUSH',
    PLOP      = 'PLOP',
    ...
};

Now, that same message looks like PLOP in textual representation. It is immediately obvious what the message means.

But the integer value that has such textual representation is system specific, which brings us to what you mentioned:

I read it's not portable

And this is when multi-chraracter constant is not useful: When writing portable programs. Microsoft Detours Library that you used as the example presumably does not care about portability.

Upvotes: 2

Related Questions