C string append

感情迁移 提交于 2019-12-07 14:47:36

问题


I've got two C strings that I want to append and result should be assigned to an lhs variable. I saw a static initialization code like:

char* out = "May God" "Bless You";.

The output was really "May GodBless You" on printing out. I understand this result can be output of some undefined behaviour.

The code was actually in production and never gave wrong results. And it was not like we had such statements only at one place. It could be seen at multiple places of very much stable code and were used to form sql queries.

Does C standard allow such concatenation?


回答1:


Yes, it is guaranteed.

Extract from http://en.wikipedia.org/wiki/C_syntax#String_literal_concatenation :

Adjacent string literals are concatenated at compile time; this allows long strings to be split over multiple lines, and also allows string literals resulting from C preprocessor defines and macros to be appended to strings at compile time




回答2:


Yes. this concatenation is allowed in C, it is not undefined behavior.

Although I think it should produce "May GodBless You" (since there is no space in the quoted part)




回答3:


The Standard says

5.1.1.2 Translation phases

6. Adjacent string literal tokens are concatenated.

So, the Solaris compiler was doing the right thing.



来源:https://stackoverflow.com/questions/5977898/c-string-append

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!