7

Why is empty struct in C a constraint violation? Why does this rule get changed in C++?

Are there any historical reasons?

3

2 Answers 2

8

since you don't have inheritance in C you don't need them. If you just want to have a distinguishable pointer type you can use pointers to incomplete types.

struct opaque;

struct opaque* stranger = 0;

should work fine.

Sign up to request clarification or add additional context in comments.

2 Comments

I figured you are a macro expert. Could you please look at stackoverflow.com/questions/5355241/… whether there is any improvement possible? Thanks!
@Johannes, I will be busy this afternoon. Have a look into P99 (through my blog). Or contact me offline tonight.
3

My guess is this:

In C, there isn't inheritance, templates, and function overloading - three major reasons we use empty structs in C++ - as a base interface, as a template parameter, as a type to help overload resolution.

Can you think of any real use of an empty struct in C?

10 Comments

@Nawaz: Maybe, maybe, I specifically mentioned this was just a guess :)
@Nawaz: I disagree: The mere fact that an empty struct CAN be used as a handle doesn't mean it has to. void*, int, etc. are perfectly good handles too. And using empty structs vs void* without inheritance and overloading isn't really any more advantageous.
@Armen: Handles of type void* can be mixed. You can pass handle to pen to a function which accept brush and the compiler would not detect there is a problem. But if you use empty structs, that would give compile time error. Means, handles of empty_pen* and empty_brush* cannot be mixed. The latter is type-safe!
@nawaz: You don't need it for that anyway, because you can just leave the types undefined. struct pen; struct brush;.
|

Your Answer

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.