2

The following code compiles and runs fine:

#include <stdio.h>

typedef int Someint;
typedef int Someint;

int main()
{
    Someint b = 4;
    printf("%d", b);
    return 0;
}

The following code doesn't compile. It's giving me an error conflicting types for 'Somestruct'.

#include <stdio.h>

typedef struct
{
    int x;
}
Somestruct;

typedef struct
{
    int x;
}
Somestruct;

int main()
{
    Somestruct b;
    b.x = 4;
    printf("%d", b.x);
    return 0;
}

Why can I typedef one type (int in first code) twice without error ,but the same thing fails for another type (the structure above)? What is the difference between the two cases? I'm using the MinGW compiler that came with CodeBlocks 12.11.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Slaven Glumac
  • 543
  • 9
  • 19
  • 3
    possible duplicate of [Repeated typedefs - invalid in C but valid in C++?](http://stackoverflow.com/questions/8594954/repeated-typedefs-invalid-in-c-but-valid-in-c) – unwind May 07 '13 at 09:04
  • Did you read the compiler output? Didn't it say `... previous declaration of Somestruct ...`? – devnull May 07 '13 at 09:05
  • The question is about why the behaviour is different between the `int` and the `struct` case. Nobody seems to be reading the question properly. – Graham Borland May 07 '13 at 09:06
  • @unwind not sure about the duplicate status, because that one is about named structs and this is about anonymous, but man, guys there do know the standard! – Ciro Santilli OurBigBook.com Sep 18 '14 at 06:35

2 Answers2

6

The thing is that when you do:

typedef struct
{

} Somestruct;

It creates an anonymous struct - you can expect some hidden implementation-defined guaranteed-unique placeholder identifier to be used - for which you specify the typedef. So, when you do it twice you get a conflict in having the same typedef-ed name asked to refer to two distinct structures. With int, you're simply repeating the original. If you give the struct an actual name then that lets you repeat the typedef:

typedef struct Somestruct
{

} Somestruct;
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
5

Because you're defining your typedef using an anonymous struct, both definitions are distinct.

The following doesn't do this, and works. (note that you can still only define the struct once)

#include <stdio.h>

typedef struct foo
{
    int x;
}
Somestruct;

typedef struct foo Somestruct;
Hasturkun
  • 35,395
  • 6
  • 71
  • 104