在形如struct structName varName;的语句中,struct是必须的吗?这是一个显而易见的语法问题,但却容易被忽略,尤其容易被C+C++的同志们忽略。
  在标准C中,struct关键字是必须的:

1
2
3
4
5
6
7
8
9
10
struct structName {
    int n;
};
//~ typedef struct structName structName;
int
main()
{
    struct structName n;
    return 0;
}

若没有前置的struct关键字,上面的代码就不能通过编译。我的gcc会提示”structName” undeclared, parse error before ‘n’的错误。为了方便,通常会使用typedef struct structName structName;语句来为struct structName定义类型别名。
  但是,在C++中,一般情况下,struct/class关键字就不是必须的。但是,在有些情况下struct/class关键字又是必须的,因为这时的名字structName有歧义性。这是因为,C/C++语言允许用户自定义类型和函数同名。

1
2
3
4
5
6
7
8
9
10
11
12
struct structName {
    int n;
};
void structName() {
    ;
}
int
main()
{
    structName n;
    return 0;
}

上面代码,无论使用gcc还是g++,都不能通过编译,即使structName n;明显只能是一个变量定义语句。这时,就需要明确使用关键字struct,即struct structName n;

Tags: ,.
你好!除了代码,此处没有多少原创之物,皆为本人搜集、整理、总结之记录与心得,欢迎转载分享!转载时请尽量注明出处,将不胜感激。祝你健康、快乐!
Home

Be the first to comment on this entry.

Name(required)
Mail (required),(will not be published)

RFC: Request For Comments. Orz..

Website(recommended)