compiling in C++ not in C

Apr 27, 2010 at 4:29pm
Can someone explain me why this program is compiling in g++ but giving error in gcc
1
2
3
4
5
6
7
8
9
#include <stdio.h>
struct size
{
    int a;
};
int main()
{
    printf("%d",sizeof(size));
}
Apr 27, 2010 at 4:31pm
Try
1
2
3
4
typedef struct 
{
    int a;
} size;
Apr 27, 2010 at 4:34pm
In C, there's three ways you can declare structs:
1
2
3
4
5
6
7
8
9
//1
struct id{};

//2
typedef struct{}id;

//3
struct id{};
typedef struct id id;
With #1, the type's name is 'struct id'. With #2, it's 'id'. With #3, it's 'struct id' or 'id' (structs and typedefs occupy different namespaces).
Apr 27, 2010 at 4:45pm
@helios
Wow! I didn't know that. C++ books don't teach that.
Apr 27, 2010 at 4:50pm
closed account (1yR4jE8b)
Don't forget:

typedef struct Foo {} Bar;
Apr 28, 2010 at 8:29am
hhmmm!! So its b'coz C++ implicitly add the word "struct" before size but not C
Apr 28, 2010 at 9:45am
As helios said, C uses different name spaces for all struct-names and all other names (typedefs, build-in types etc). As C evolved to C++, Bjarne Stroustrup thought this is useless and removed it. Hence, in C++ all types share the same name space.

(Not to be confused with the C++-feature "namespace" which is ... "similar but different" :-D)

The "struct" is just to tell the C-compiler in which type table he should look. There is no other difference. Code that uses a typedef compiles to the exact same binary as one that annotates the structs with "struct type". (Ok.. it differs in the debug symbol list ;)

Ciao, Imi.
Last edited on Apr 28, 2010 at 9:46am
Apr 28, 2010 at 12:04pm
closed account (z05DSL3A)
In C, a struct name is not automatically a type name, as it is in C++.

1
2
3
4
5
6
7
8
struct  point_t{ int x; int y; };

// In C++, point_t is automatically a type name so this is valid
point_t origin;

//In C, you have to use the elaborated form
struct  point_t origin;


There is only one way of defining struct (above) and its type is a structure type.

typedef is used to give the structure type a new name.

1
2
3
4
5
6
7
struct  point_t{ int x; int y; };
typedef struct point_t point_t; 

// now both C and C++ can do this
point_t origin;
struct  point_t pt;  


For more information read up on Elaborated Type Specifier.
Topic archived. No new replies allowed.