You may have noticed that functions can only return one variable. But what if want to return more information than we can hold in one variable? The answer is to pack multiple variables together into a single structure. This creates a new type of variable which contains a number of fields. In this section's example, we create a new type of variable called struct SquareData. We can declare this just like other variables -- instead of writing int or float, we write struct SquareData.
After we have declared a variable of this type with: struct SquareData mySquare;
we can access its fields with mySquare.side, mySquare.area or any other field name after the period.
Returning a struct is a modern addition to the language. It was not supported in the original C standard in 1972, but was added in the ANSI C standard (also sometimes known as "C89" or "C90"). Some very old compilers might not support ANSI C. We will see another way to return multiple values in a few weeks.
Structure:
- #include <stdio.h>
- struct SquareData {
- float area;
- float perimeter;
- int side; };
- struct SquareData calcSquare(int x) { //define variable of data type structure
- struct SquareData mySquare;
- mySquare.side = x;
- mySquare.perimeter = 4*x;
- mySquare.area = x*x;
- // we need to return this to main()
- return mySquare; }
- void printStuff(struct SquareData mySquare) { // this is not useful here, but it works
- float areaBAD = mySquare.area;
- printf("The square's sides are ");
- printf("%i units long, ", mySquare.side);
- printf("and thus has \nan area of ");
- printf("%f units, and ", areaBAD);
- printf("a perimeter of ");
- printf("%f units.\n", mySquare.perimeter); }
-
- int main() {
- struct SquareData square;
- square = calcSquare(2);
- printStuff(square);
- getchar();
- return 0;
- }
复制代码
|