gpt4 book ai didi

c++ - C 风格/C++ 正确性,struct/union/enum 标记是否与类型名称相同?

转载 作者:IT老高 更新时间:2023-10-28 23:02:09 24 4
gpt4 key购买 nike

下面的 MyStruct 定义(标记 MyStruct)和类型 MyStruct 的类型定义似乎完全可以被 gcc(至少 4.6.2)和 g++ 编译。

typedef struct MyStruct {
int a;
int b;
} MyStruct;

我的问题是:使用与类型名称相同的标签名称是否容易出错(在 C 和/或 C++ 中)或风格不好?

根据http://www.eetimes.com/discussion/programming-pointers/4024450/Tag-vs-Type-Names不是:

I've never understood why they use different names for the tag and the typedef when one name will do just fine:

typedef struct tree_node tree_node;

但我经常看到类似以下样式的代码:

  1. typedef struct tagMyStruct {...} MyStruct;
  2. typedef struct myStruct {...} MyStruct;`
  3. typedef struct _MyStruct {...} MyStruct; <是的,我知道下划线+大写字母

在每种情况下,都有人在某种程度上使标签名称​​与类型名称不同。这背后有什么实际原因吗?

旁注:我使用 C++ 编译器,但我希望 C 与这些定义兼容(我知道这对 c++ 来说是不好的风格)。出于维护某些调试工具可用性的原因,我需要所有标记名称都有意义(不是自动生成的 __unknown_something 标记,以防未命名的结构,例如,在 Visual Studio 类 View 中查看)。

同样的问题/问题适用于 union 和枚举。

最佳答案

语言方面,在 C 和 C++ 中都可以,因为标签名称存在于单独的 namespace 中(不是 namespace)。

在 C++ 中,使用 typedef 绝对是一种不好的风格,因为它是多余的。你可以同时使用 MyStructstruct MyStruct 无论你是否有 typedef

如果您认为 C 兼容性比 C++ 风格更重要,那是您的选择。 :-)

关于c++ - C 风格/C++ 正确性,struct/union/enum 标记是否与类型名称相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9534884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com