Page 38 - Programming Microcontrollers in C
P. 38

Other Types      23

                          anything to the union destroys any data previously stored to the
                          union.

            The struct
                              Yet another type is the struct. The struct is a collection of
                          things much like the array. In the case of the struct, there are two
                          major differences. A struct can contain different types, and the
                          struct itself is a first class type. An array must be a collection of
                          like types, and an array is NOT a type, so the type-like things you
                          can do with a struct are not available for an array.
                              You create a struct in much the same form as was seen with a
                          union. You may use a tag name.

                   struct able
                   {
                       char a,b;
                       int c,d;
                   };
                          This struct is made up of two characters and two integers. If you
                          wish to define an instance of the struct, you should use

                   struct able here:
                          Access the members of the struct with the dot operator like

                   here.a = ‘a’;
                   here.b = 16;
                   here.c = 32000;
                   here.d = -16500;

                              We will see more of struct in Chapter 2 where you will learn
                          how to make use of the new types created by struct.

                          EXERCISES
                          1. Write a program that reads all of the characters from an input file
                            and prints the characters on the screen. Use the getchar() func­
                            tion used earlier to read the inputs and the putchar(c) to print
                            the results to the screen.
                          2. Modify the above program to count the number of characters in an
                            input stream.
   33   34   35   36   37   38   39   40   41   42   43