Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

Why does C need "struct" keyword and not C++?

I've always been a little confused about what's going on here:

#include <stdio.h>

int main() {  
    timeval tv;
    tv.tv_sec = 1;

    for (;;) {
        select(0, 0, 0, 0, &tv);
        printf("%s
", "Hello World!");
    }
}

Sorry if that doesn't compile, just wrote it as a quick example.

Code like this won't compile under gcc unless I add the keyword struct prior to the use of the struct timeval. g++ on the other hand handles it fine as is.

Is this a difference between how C and C++ handle structures or is it just a difference in the compilers? (I'm very C++ oriented, and the use of struct in C on lines like this has always somewhat baffled me).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Syntactically both treat struct almost the same. Only C++ has added an extra rule that allows to omit the struct (and class) keyword if there is no ambiguity.

If there is ambiguity, also C++ requires the struct keyword in some places. A notorious example is stat on POSIX systems where there is a struct stat and a function stat.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...