Why can a string literal be implicitly converted to char* only in certain case? [duplicate]

こ雲淡風輕ζ 提交于 2019-12-04 00:31:16

This behaviour differs between C and C++, at least in theory.

In C: a string literal decays to a non-const pointer. However, that doesn't make it a good idea; attempting to modify the string through that pointer leads to undefined behaviour.

In C++: it's never ok (AFAIK).* However, some compilers may still let you get away with it. GCC, for example, has the -Wwrite-strings flag, which is enabled by default (at least in 4.5.1 onwards).


* In C++11, at least. (I don't have older specs to hand.)

The difference between

f("Hello");

and

f(p);

is that the former involves a literal. In C++03 conversion from string literal to char* (note: not const) was supported. It isn't supported any longer in C++11, but few if any compilers have yet caught up with that rule change.

f("Hello");

Even this is not okay in C++. The compiler should give diagnostic, or else it needs to be updated.

In C++, "Hello" is convertible to const char*, not char*.

The conversion from "Hello" to char* is allowed in C++03, though it is deprecated. And in C++11, the conversion is invalid, and the code is ill-formed.

I think because auto keyword. it's type deduction so compiler doesn't know it how to convert to char* anymore.

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