简体   繁体   中英

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 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. In my opinion CHAR alone should not work, it should always be CHAR[10].

Moreover, if I change fun declaration to accept std::string& instead of std::string, it throws a compilation error. I am not sure why.

This is a confusing part of C declarator syntax, and doesn't do what you think it does.

Throw away logic and follow the spiral rule .

What you think it does

Makes CHAR[10] mean char .

What it actually does

Makes CHAR mean char[10] .

That's why using CHAR "on its own" is perfectly valid here, if remarkably stupid. I mean, seriously, typedeffing a fixed-size array in the first place is pretty dumb, but naming it CHAR takes the biscuit.

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* . However, that code is cause for undefined behavior since c has not been initialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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