Structures and Unions

After you declare a structure or union having a tag, you can use the tag as a type name in C++:

struct duo
{
        int a;
        int b;
};
struct duo m;  /* valid C, C++ */
duo n;        /* invalid C, valid C++ */

As a result, a structure name can conflict with a variable name. For example, the following program compiles as a C program, but it fails as a C++ program because C++ interprets the duo in the printf() statement as a structure type rather than as the external variable:

#include <stdio.h>
float duo = 100.3;
int main(void)
{
    struct duo { int a; int b;};
    struct duo y = { 2, 4};
    printf ("%f\n", duo);   /* ok in C, not in C++ */
    return 0;
}

In C and in C++, you can declare one structure inside another:

 struct box { struct point {int ...

Get C Primer Plus®, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.