“ hello world”字符串文字可以分配给char *类型吗? [英] "hello world" string literal can be assigned to char * type?

查看:80
本文介绍了“ hello world”字符串文字可以分配给char *类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char* foo = "fpp"; //compile in vs 2010 with no problem

我虽然字符串文字是const char *类型。

不能将const类型分配给非const类型。

所以我希望上面的代码失败或我错过了什么?

I though string literal is const char* type.
And const type cannot be assigned to non-const type.
So I expect the code above to fail or am I missing something?

编辑:对不起,我完全忘记了编译器也会发出警告。

我一直都在查看错误列表。

我忘了检查一下。

Sorry guys, I totally forgotten that compiler throws warning too.
I was looking at error list all this time.
I'm forget to check that.

Edit2:我将项目警告级别设置为EnableAllWarnings(/ Wall),对此没有警告。

所以我的问题仍然有效。

I set my project Warning Level to EnableAllWarnings (/Wall) and there's no warning about this.
So my question is still valid.

推荐答案

据我所知,在C中,在添加 const 之前,这是将字符串分配给指针的方法。

As I understand it, in C, before const was added, this was the way to assign a string to a pointer.

在C ++中,这是已弃用的行为,但仍然可以保持向后兼容性。因此,请不要使用它。

In C++ this is deprecated behavior, but still allowed to keep backwards compatibility. So don't use it.

事实上,我相信在C ++ 11中它完全无效。

In fact, I believe in C++11 it's completely invalid.

这篇关于“ hello world”字符串文字可以分配给char *类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆