C - string + int, syntax explanation?

Status
Not open for further replies.

agifford

Ars Tribunus Militum
2,142
C syntax/language question. Musl's iconv implementation is generating clang warnings about adding integers to strings in its iconv implementation.

I'd love to improve the code to silence the warnings, but i'm not sure what its supposed to do, assuming the code is correct.
What does the string + integer actually do? despite the wanings.

From musl iconv.c:318

Code:
unsigned c;
...
x += iconv((iconv_t)(uintptr_t)to,
						&(char *){"\303\212\314\204"
						"\303\212\314\214"
						"\303\252\314\204"
						"\303\252\314\214"
						+c%256}, &(size_t){4},
						out, outb);

The "\303\252\314\214"+c%256 is where the warning is from.
 

Jonathon

Ars Legatus Legionis
17,644
Subscriptor
It's adding to the address of the string.

Whether or not that's meaningful depends on the value of c. If it's less than 16 (the length of that string), you'll get a pointer that points somewhere in the middle of the string (depending on the value of c). If it's larger than 16, it'll point outside the string and an attempt to access it will result in undefined behavior (at best, a crash; at worst, unexpected behavior elsewhere in your program).
 
Here's the exact warning:

Code:
iconv.c:323:7: warning: adding 'unsigned int' to a string does not append to the string [-Wstring-plus-int]
                                                +c%256}, &(size_t){4},
                                                ^~~~~~
iconv.c:323:7: note: use array indexing to silence this warning
                                                +c%256}, &(size_t){4},
                                                ^

The note would include the exact code to add if the string were all on one line. Instead of

Code:
&(char*){"\303\212...\314\214"+c%256}

it says to use:

Code:
&(char*){&"\303\212...\314\214"[c%256]}
 

agifford

Ars Tribunus Militum
2,142
thanks all. Yeah i wasn't sure on how the code was supposed to be working, Almost looked like it had been borrowed from another language where you could add a single character to the end of a string.

wound up silencing the warning with a #pragma, since it looks like it could overrun the array anyway so a real fix would take more effort for code its unlikely i'd ever run. (famous last words).
 
Status
Not open for further replies.