In C one can do this
printf("%c", *("hello there" 7));
which prints h
How can a read-only string literal like "hello there" be used almost like a pointer? How does this work exactly?
CodePudding user response:
While you know how it is stored you will understand.
String constants are stored in .rodata section, seperate from code which stored in .text section. So when the program is running, it need to know the address of those string constants when using them, and, length of strings and arrays are not all the same, there is no simple way to get them (integer and float can be stored in and passed by register), thus "strings as arrays are visited thought pointer".
Actually values not able to be hard encodered in instructions are all stored in sections such as .data and .rodata.
CodePudding user response:
Using 'anonymous' string literals can be fun.
It's common to express dates with the appropriate ordinal suffix. (Eg "1st of May" or "25th of December".)
The following 'collapses' the 'Day of Month' value (1-31) down to values 0-3, then uses that value to index into a "segmented" string literal. This works!
// Folding DoM 'down' to use a compact array of suffixes.
i = DoM;
if( i > 20 ) i %= 10; // Change 21-99 to 0-9.
if( i > 3 ) i = 0; // Every other one ends with "th"
// 0 1 2 3
suffix = &"th\0st\0nd\0rd"[ i * 3 ]; // Acknowledge 3byte regions.