难道" const的"仅仅意味着只读或更多的东西? [英] Does "const" just mean read-only or something more?

查看:165
本文介绍了难道" const的"仅仅意味着只读或更多的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是什么常量究竟意味着什么?只读似乎来封装它的意义对我来说,可是,我不知道我是对的。

What does const really mean? Read-only seems to encapsulate its meaning for me, but, I'm not sure I'm right.

如果只读和常量是不同的,有人能告诉我为什么吗?

If read-only and const are different, could someone tell me why?

是什么促使这个问题是这个答案他指出常量刚是指只读C.我以为那是的所有常量的意思,不管它是否是C或C ++。他是什么意思?

What prompted this question was this answer where he states const "just" means read-only in C. I thought that's all const meant, regardless of whether it was C or C++. What does he mean?

有关答复的具体差异常量用C VS C ++中,我创建了一个新问题:的如何" const的"在C和C ++有什么不同?按 - [R ..的建议。

For an answer to the specific differences in const in C vs C++, I've created a new question: How does "const" differ in C and C++? as per R..'s suggestion.

推荐答案

通过声明一个变量常量表示您没有修改该变量的意图编译器。不过,这并不意味着人无我有!这只是让一些优化,并通过编译错误通知(注意,这是大多编译错误,而常量==只读将意味着运行时错误)。

By declaring a variable as const you indicate compiler that you have no intentions of modifying that variable. But it does not mean others don't have! It's just to allow some optimization and to be notified by a compile error (note, that it's mostly compile error, while const == ReadOnly would mean runtime errors).

常量并不意味着的只读的,因为你可以写 const的挥发,这将意味着的它可以自行随时更改,但我不打算修改它。

const does not mean read only, because you can write const volatile, that would mean it could change by itself anytime, but I have no intentions to modify it.

编辑:这是一个经典的例子:考虑我写了code,它读取内存映射端口当前时间。考虑到RTC映射到内存DWORD 0x1234的。

here is a classical example: consider I'm writing the code that reads current time from a memory-mapped port. Consider that RTC is mapped to memory DWORD 0x1234.

const volatile DWORD* now = *(DWORD*)0x1234;

这是常量,因为它是一个只读端口,它的挥发性因为每次我会读它,它会发生变化。

It's const because it's a read-only port, and it's volatile because each time I will read it it will change.

另外请注意,许多体系有效地使声明为常量全球varialbles 只读的,因为它是UB修改它们。在这种情况下UB将自己表现为一个运行时错误。在其他情况下,这将是一个真正的UB:)

Also note that many architectures effectively makes global varialbles declared as const read-only because it's UB to modify them. In these cases UB will manifest itself as a runtime-error. In other cases it would be a real UB :)

这是一个良好的阅读:<一href=\"http://publications.gbdirect.co.uk/c_book/chapter8/const_and_volatile.html\">http://publications.gbdirect.co.uk/c_book/chapter8/const_and_volatile.html

这篇关于难道&QUOT; const的&QUOT;仅仅意味着只读或更多的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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