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?

7
  • 2
    What do you mean by "structs as classes without methods"? And what has a typedef got to do with that?
    – amon
    Feb 14, 2020 at 18:52
  • @amon struct foo { ... }; vs typedef struct { ... } foo_t;
    – Caleth
    Feb 14, 2020 at 18:54
  • 1
    @Caleth yes but what does that typedef have to do with OOP?
    – amon
    Feb 14, 2020 at 19:35
  • What does the language C have to do with object-oriented programming? 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 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;
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.