Since I cut my teeth on code with OO, I’m biased toward using structs as classes without methods. However, there’s probably a good reason that typedef isn’t the default behavior of struct. What is it?
1 Answer
C doesn't offer custom namespaces as C++ does, but it's untrue that C doesn't have namespaces at all. Functions and structures are in different namespaces:
#include <stdio.h>
void Test ( ) {
printf("Hello World\n");
}
struct Test {
int field1;
int field2;
};
int main ( ) {
struct Test t = { 0, 1 };
Test();
return 0;
}
When you typedef
, you are forcing structures into the same namespace as functions:
#include <stdio.h>
typedef struct {
int field1;
int field2;
} Test;
void Test ( ) {
printf("Hello World\n");
}
int main ( ) {
Test t = { 0, 1 };
Test();
return 0;
}
results in
main.c:8:6: error: ‘Test’ redeclared as different kind of symbol
void Test ( ) {
^~~~
main.c:6:3: note: previous declaration of ‘Test’ was here
} Test;
struct foo { ... };
vstypedef struct { ... } foo_t;
struct
objects are just as object-like regardless of whether you use thetypedef
keyword