Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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\n", "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).

like image 222
John Humphreys Avatar asked Dec 07 '11 21:12

John Humphreys


People also ask

Why we use struct keyword in C?

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).

What's the difference between struct and typedef?

Basically struct is used to define a structure. But when we want to use it we have to use the struct keyword in C. If we use the typedef keyword, then a new name, we can use the struct by that name, without writing the struct keyword.

Does C have struct?

In C programming, a struct (or structure) is a collection of variables (can be of different types) under a single name.

Is it possible to omit the keyword struct while declaring structure variable justify?

yes but the compiler-driver decides to which libraries the code will be linked.


1 Answers

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.

like image 58
Jens Gustedt Avatar answered Sep 18 '22 07:09

Jens Gustedt