[ fromfile: classes.xml id: structs ]
In the C language, the struct
keyword enables the programmer to define a structured chunk of memory that can store a heterogeneous set of data.
Example 2.1 shows the definition of a structured piece of memory composed of smaller chunks of memory.
Example 2.1. src/structdemo/demostruct.h
[ . . . . ] struct Fraction { int numer, denom; string description; }; [ . . . . ]
Each smaller chunk (numer, denom, description
) of the struct
is accessible by name.
The smaller chunks are called data members or, sometimes, fields.
Code that is external to the struct
definition is called client code.
Example 2.2 shows how client code can use a struct
as a single entity.
Example 2.2. src/structdemo/demostruct.cpp
[ . . . . ] void printFraction(Fraction f) { cout << f.numer << "/" << f.denom << endl; cout << " =? " << f.description << endl; } int main() { Fraction f1; f1.numer = 4; f1.denom = 5; f1.description = "four fifths"; Fraction f2 = {2, 3, "two thirds"}; f1.numer = f1.numer + 2; printFraction(f1); printFraction(f2); return 0; } Output: 6/5 =? four fifths 2/3 =? two thirds
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |