在外部声明非常量变量'const'是否合法C? [英] Is it legal C to declare a non-const variable 'const' externally?

查看:65
本文介绍了在外部声明非常量变量'const'是否合法C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个文件window.h,它定义了:

Say I have a file, window.h, which defines:

extern const int window_width, window_height;

我不希望任何人更改这些变量,因此对于window.h的所有包含者而言,它们都是常量.但是,在源文件中声明它们为非常量合法吗?

I don't want anyone to change these variables, so they're const for all includers of window.h. However, is it legal to declare them non-const in the source file?

// window.c
int window_width, window_height;

void onResizeWindow(int w, int h) {
    window_width = w;
    window_height = h;
}

在Apple clang版本12.0.0(clang-1200.0.22.7)中,此编译对我而言没有链接器错误.但这是合法且定义明确的C吗?

This compiles without linker errors for me in Apple clang version 12.0.0 (clang-1200.0.22.7). But is it legal and well-defined C?

推荐答案

否,它是未定义的行为.同一对象的两个声明必须具有兼容的类型,并且非 const 限定类型与该类型的 const 限定版本不兼容.(与涉及两个或多个翻译单元的其他问题一样,这种不确定的行为不需要诊断.但是缺少诊断消息并不表示可以.这仅意味着编译器仅在一个翻译单元中查看一个翻译单元.时间,因此看不到不一致的地方.)

No, it is undefined behaviour. Two declarations for the same object must have compatible types, and a non-const-qualified type is not compatible with the const-qualified version of the same type. (Like other issues which involve two or more translation units, this undefined behaviour does not require a diagnostic. But the absence of a diagnostic message doesn't mean that it's OK. It just means that the compiler only looks at one translation unit at a time, so it can't see inconsistencies.)

使用指向 const 限定类型的指针访问该类型的非 const 对象,甚至使用指向一种非 const 限定类型,用于读取(但不突变) const 限定的对象.但是请注意,只要变量的实际定义不是 const 限定的,放弃" const "也不是错误.从指针开始,并使用它来修改变量.

It is not an error to use a pointer to a const-qualified type to access a non-const object of that type, or even to use a pointer to a non-const qualified type to read from (but not mutate) a const-qualified object. But be aware that as long as the actual definition of the variable is not const-qualified, it is also not an error to "cast away const" from a pointer and use it to modify the variable.

这篇关于在外部声明非常量变量'const'是否合法C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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