0

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?

asked Feb 14, 2020 at 18:33
7
  • 2
    What do you mean by "structs as classes without methods"? And what has a typedef got to do with that? Commented Feb 14, 2020 at 18:52
  • @amon struct foo { ... }; vs typedef struct { ... } foo_t; Commented Feb 14, 2020 at 18:54
  • 1
    @Caleth yes but what does that typedef have to do with OOP? Commented Feb 14, 2020 at 19:35
  • What does the language C have to do with object-oriented programming? Commented Feb 14, 2020 at 19:37
  • 1
    @JohnnyApplesauce it makes no difference. struct objects are just as object-like regardless of whether you use the typedef keyword Commented Feb 15, 2020 at 0:46

1 Answer 1

8

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;
answered Feb 15, 2020 at 1:13
1
  • Very enlightening! Commented Feb 15, 2020 at 3:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.