简体   繁体   English

相同定义的类型重新定义

[英]Type redefinition of identical definition

If I wanted to use a type, let's say ulong (part of POSIX), but did not know whether it was defined already, is it guaranteed that redefinition with the same definition is benign?如果我想使用一个类型,比如说ulong (POSIX 的一部分),但不知道它是否已经定义,是否保证使用相同定义的重新定义是良性的? This works in GCC, but I am unsure if it is defined in the C Standard.这适用于 GCC,但我不确定它是否在 C 标准中定义。

Example例子

#include <stdio.h>
#include <sys/types.h>  // POSIX

/* 'ulong' already defined as 'unsigned long' */

typedef unsigned long ulong; // (Benign?) redefinition

int main(void) {
    ulong n = 5;

    printf("Result: %ld\n", n);
    return 0;
}

Short Answer简答

Yes, this is guaranteed by C11 and later, and C++98 and later.是的,C11 及更高版本以及 C++98 及更高版本保证了这一点。

Long answer长答案

For C, Section 6.7.3 of the C11 Standard states:对于 C,C11 标准的第 6.7.3 节规定:

- a typedef name may be redefined to denote the same type as it currently does,provided that type is not a variably modified type; - 可以重新定义typedef名称以表示与当前相同的类型,前提是该类型不是可变修改的类型;

This means that a type may be redefined so long as each definition is identical.这意味着只要每个定义相同,就可以重新定义类型。 Section 6.7.5 goes even further to state that only the first of these definitions (or the only definition) will be used by the compiler.第 6.7.5 节更深入到 state,编译器将只使用这些定义中的第一个(或唯一的定义)。

For C++, Section 7.1.3.3 of the C++98 Standard states:对于 C++,C++98 标准的第 7.1.3.3 节规定:

In a given scope 1 , a typedef specifier can be used to redefine the name of any type declared in that scope to refer to the type to which it already refers.在给定的 scope 1中, typedef说明符可用于重新定义在 scope 中声明的任何类型的名称,以引用它已经引用的类型。

This means that type redefinition is allowed in any non-class scope.这意味着在任何非类 scope 中都允许重新定义类型。 Furthermore, in Section 7.1.3.6, it states:此外,在第 7.1.3.6 节中,它指出:

In a given scope, a typedef specifier shall not be used to redefine the name of any type declared in that scope to refer to a different type.在给定的 scope 中,不应使用typedef说明符来重新定义在 scope 中声明的任何类型的名称以引用不同的类型。

This means that redefinition is disallowed when the definition ( type , in the documentation) is changed.这意味着当定义(文档中的type )更改时,不允许重新定义。 As a result, the only time when we are unable to redefine a type is when subsequent definitions differ from the first, or--as Section 7.1.3.8 states--if the type name describes any of the following:因此,我们无法重新定义类型的唯一情况是后续定义与第一个定义不同,或者 - 如第 7.1.3.8 节所述 - 如果类型名称描述了以下任何内容:

  • an elaborated type specifier详细的类型说明符
  • a class definition一个 class 定义
  • a constructor declaration, or构造函数声明,或
  • a destructor declaration析构函数声明

source: https://port70.net/~nsz/c/来源: https://port70.net/~nsz/c/

1 In C++03 and later, scope must be non-class 1在 C++03 及更高版本中,scope 必须是非类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM