Thread: who can help me?

  1. #1
    Registered User
    Join Date
    Nov 2007

    who can help me?

    As we all know that in many C/C++ compilers the size of a null stucture is 1.
    So,what is the usage of a null structure?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    A "null" structure, as in an empty class or struct, is sometimes used to create a type of pointer that can be differentiated from other pointers by the compiler.

    struct a {};
    struct b {};
    void func1(struct a *p);
    void func2(struct b *p);
    Now you can guarantee that the compiler gives an error if you pass a strcut b pointer to func1, or a struct a pointer to func2.

    Particularly useful when using so called "opaque pointers", e.g. a handle or some such - by declaring a pointer to an empty structure, you can differentiate a file-handle from a graphics-display-handle, but you don't have to tell the calling code what the CONTENTS of these two structures are - just that there is a structure of type "file" or "graphicsHandle".

    You can even use a script/preprocessor to "process" your actual header file to "strip" the structure so that it's empty when you produce the "external" header file from the "internal" header file.

    The code that implements for example func1 & func2 above, would of course have the full content of struct a and struct b available to process this information.

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > As we all know that in many C/C++ compilers the size of a null stucture is 1
    As fewer people know, C is not the same as C++, nor a subset(*) of C++.

    Nor is C/C++ any known programming language, but some mish-mash mutation unique to every user who claims to program in it.

    For one thing, an empty struct is actually illegal in C, but legal in C++.

    $ cat foo.c
    #include <stdio.h>
    struct empty {
    int main ( ) {
        printf( "&#37;ld\n", sizeof(empty) );
        return 0;
    $ gcc foo.c
    foo.c: In function `main':
    foo.c:5: error: `empty' undeclared (first use in this function)
    foo.c:5: error: (Each undeclared identifier is reported only once
    foo.c:5: error: for each function it appears in.)
    $ g++ foo.c
    $ ./a.exe
    (*) C is a semantic subset, in that every C concept can be expressed in a C++ program, but it is far from being a syntactic subset, in that all the extra C++ keywords (like class) are perfectly valid C identifiers.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed