-2

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
    What do you mean by "structs as classes without methods"? And what has a typedef got to do with that? – amon Feb 14 at 18:52
  • @amon struct foo { ... }; vs typedef struct { ... } foo_t; – Caleth Feb 14 at 18:54
  • @Caleth yes but what does that typedef have to do with OOP? – amon Feb 14 at 19:35
  • What does the language C have to do with object-oriented programming? – BobDalgleish Feb 14 at 19:37
  • It makes structs feel more object like if I’m only writing the struct’s name in the declaration. – JohnnyApplesauce Feb 14 at 19:43
4

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;
New contributor
Mecki is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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