Structures and Unions

I l @ ve RuBoard

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 x; int y; } upperleft;     struct point lowerright; }; 

In C, you can use either structure later, but C++ requires a special notation for the nested structure:

 struct box ad;     /* valid C, C++         */ struct point dot;  /* valid C, invalid C++ */ box::point dot;    /* invalid C, valid C++ */ 
I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net