简体   繁体   English

“ typedef char CHAR [10];”是什么意思?

[英]What is the meaning of “typedef char CHAR[10];”?

Came across a piece of code which defined and used a typedef it like below: 遇到了一段定义和使用typedef的代码,如下所示:

typedef char CHAR[10];
void fun(std::string s) {}
int main()
{
    CHAR c;
    fun(c);
 }

And strangely this works. 奇怪的是,这可行。 My question is why define and use a typedef like this and how it works. 我的问题是为什么要定义和使用像这样的typedef及其工作方式。 In my opinion CHAR alone should not work, it should always be CHAR[10]. 在我看来,仅CHAR不应起作用,而应始终为CHAR [10]。

Moreover, if I change fun declaration to accept std::string& instead of std::string, it throws a compilation error. 此外,如果我更改fun声明以接受std :: string&而不是std :: string,它会引发编译错误。 I am not sure why. 我不知道为什么。

This is a confusing part of C declarator syntax, and doesn't do what you think it does. 这是C声明程序语法的一个令人困惑的部分,它没有执行您认为的操作。

Throw away logic and follow the spiral rule . 抛弃逻辑并遵循螺旋规则

What you think it does 您认为它能做什么

Makes CHAR[10] mean char . 使CHAR[10]表示char

What it actually does 它实际上是做什么的

Makes CHAR mean char[10] . 使CHAR char[10]

That's why using CHAR "on its own" is perfectly valid here, if remarkably stupid. 这就是为什么“非常独自”使用CHAR在这里完全有效的原因。 I mean, seriously, typedeffing a fixed-size array in the first place is pretty dumb, but naming it CHAR takes the biscuit. 我的意思是说真的,首先,对一个固定大小的数组进行typedeff是很愚蠢的,但是将其命名为CHAR就是饼干。

typedef char CHAR[10];
void fun(std::string s) {}
int main()
{
    CHAR c;
    fun(c);
}

is equivalent to 相当于

void fun(std::string s) {}
int main()
{
    char c[10];
    fun(c);
}

Syntactically, that is correct code since a std::string can be constructed from a char* . 从语法上讲,这是正确的代码,因为std::string可以从char*构造。 However, that code is cause for undefined behavior since c has not been initialized. 但是,该代码是未定义行为的原因,因为尚未初始化c

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

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