A Little C Primer/C Variables, Declarations and Constants

C supports a flexible set of variable types and structures, as well as common arithmetic and math functions along with a few interesting operators that are unique to C. This chapter explains them in detail, and ends with a short discussion of preprocessor commands.

C includes the following fundamental data types:

These are representative values. The definitions tend to vary between implementations. For example, in some systems an "int" is 16 bits, and a "long double" could be 64 bits. The only thing that is guaranteed is the precedence:  short <= int <= long float <= double <= long double

 One peculiarity of C that can lead to maddening problems is that while there is an "unsigned char" data type, for some reason many functions that deal with individual characters require variables to be declared "int" or "unsigned int".

Declarations are of the form:   Variable names can be at least 31 characters long, though modern compilers will always support longer names. Variables names can be made up of letters, digits, and the "_" (underscore) character; the first character must be a letter. While it is possible to use uppercase letters in variable names, conventional C usage reserves uppercase for constant names. A leading "_" is also legal, but is generally reserved for marking internal library names.

C allows several variables to be declared in the same statement, with commas separating the declarations. The variables can be initialized when declared. Constant values for declarations can be declared in various formats:  128       decimal int 256u      decimal unsigned int 512l      decimal long int 0xAF      hex int 0173      octal int 0.243     float 0.1732f   float 15.75E2   float 'a'       character "giday"   string  There are a number of special characters defined in C:  '\a'    alarm (beep) character '\p'    backspace '\f'    formfeed '\n'    newline '\r'    carriage return '\t'    horizontal tab '\v'    vertical tab '\\'    backslash '\?'    question mark '\''    single quote '\"'    double quote   '\0NN'   character code in octal   '\xNN'   character code in hex   '\0'     null character  "Symbolic constants" can be specified using the "define" C preprocessor declaration:

  There is also a "const" declaration that defines a read-only variable, such as a memory location in ROM: <B> </B> <B> </B>
 * Arrays can be declared and initialized:

All C arrays have a starting index of 0, so "list" has the indexes 0 through 4. Elements in "rdata" would be accessed as follows: <B> </B> C does not perform rigorous bounds checking on array access. It is easy to overrun the bounds of the array, and the only symptom will be that the program acts very strangely.

strings:
 * Of particular importance are arrays of characters, which are used to store

<B> </B> The string "This is a test!" is used to initialize "s" through the "strcpy" function, discussed in a later chapter. The stored string will contain a terminating "null" character (the character with ASCII code 0, represented by '\0'). The null is used by C functions that manipulate strings to determine where the end of the string is, and it is important to remember the null is there.

The curious reader may wonder why the "strcpy" function is needed to initialize the string. It might seem to be easier to do: <B> </B> In fact, this is an absurd operation, but to explain why, the concept of "pointers" must be introduced.

an array. For example, a pointer could be defined named:
 * C programs can define pointers that contain the address of a variable or

<B> </B> -- that gives the address of a variable, rather than the variable itself. A value could then be put into that location with the statement: <B> </B> In an inverse fashion, the address of a variable can be obtained with "&": <B> </B> To sum up:

<UL>

<LI> A pointer is declared in the form: "*myptr".

<LI> If "myvar" is a variable, then "&myvar" is a pointer to that variable.

<LI> If "myptr" is a pointer, then "*myptr" gives the variable data for that pointer.

</UL>

Pointers are useful because they allow a function to return a value through a parameter variable. Otherwise, the function will simply get the data the variable contains and have no access to the variable itself.

One peculiar aspect of C is that the name of an array actually specifies a pointer to the first element in the array. For example, given the string declaration: <B> </B> -- then the function call: <B> </B> -- will actually pass the address of the character array to the function, and the function will be able to modify it. However: <B> </B> -- gives the value in the array value with index 12. Remember that this is the 13th element, since indexes always start at 0.

There are more peculiarities to strings in C. Another interesting point is that a string literal actually evaluates to a pointer to the string it defines. This means that in the following operation: <B> </B> -- "p" ends up being a pointer to the memory in which the C compiler stored the string literal, and "p[0]" would evaluate to "L". In a similar sense, the following operation:

<B> </B> -- would put the character "L" into the variable "ch".

This is very well and good, but why care? The reason to care is because this explains why the operation: <B> </B> -- is absurd. This statement tells the C compiler to reserve 128 bytes of memory and set a pointer named "s" to point to them. Then it reserves another block of memory to store "This is a test!" and points "s" to that. This means the block of 128 bytes of memory that were originally allocated is now sitting empty and unusable, and the program is actually accessing the memory that stores "This is a test!".

This will seem to work for a while, until the program tries to store more bytes into that block than can fit into the 16 bytes reserved for "This is a test!". Since C is poor about bounds checking, this may cause all kinds of trouble.

This is why "strcpy" is usually necessary. It isn't needed for a string that won't be modified or will not be used to store more data than it is initialized to, and under such circumstances the following statements will work fine: <B> </B>

These issues become particularly tricky when passing strings as parameters to functions. The following example shows how to get around the pitfalls: <B> </B> <B> </B> This program has a few interesting features: <UL>
 * It is possible to define "structures" in C, which are collections of different data elements:

<LI> The structure has to be defined by a "struct" declaration before it can declare any structures themselves. In this case we define a struct of  type "person".

<LI> Instances of the struct ("m") are then declared as by defining the structure type ("struct person").

<LI> Elements of the structure are accessed with a "dot" notation ("m.name",  "m.age", and "m.wage"). </UL>

A structure can be copied to another structure with a single assignment statement, as long as the structures are of the same type: <B> </B> It is also possible to declare arrays of structures: <B> </B> -- or even embed structures inside structure declarations: <B> </B> -- in which case the nested structure would be accessed as follows: <B> </B> The name of a structure defines a variable, not an address. If the name of a structure is passed to a function, the function works only on its local copy of the structure. To return values, an address must be specified: <B> </B> There is a shorthand way to get at the elements of a structure with the pointer to the structure instead of the structure itself. If "sptr" is a pointer to a structure of type "person", its fields can be accessed as follows: <B> </B> <B> </B> The difference is that the union can store either of these values, but not both at the same time. A "char" value or an "int" value can be stored in an instance of the union defined above, but it's not possible to store both at the same time. Only enough memory is allocated for the union to store the value of the biggest declared item in it, and that same memory is used to store data for all the declared items. Unions are not often used and will not be discussed further.
 * C contains a concept similar to a structure known as a "union". A union is declared in much the same way as a structure.  For example:


 * The following example program shows a practical use of structures. It tests a set of functions that perform operations on three-dimensional vectors:

<B><PRE> vadd:    Add two vectors. vsub:    Subtract two vectors. vdot:    Vector dot product. vcross:  Vector cross product. vnorm:   Norm (magnitude) of vector. vangle:  Angle between two vectors. vprint:  Print out vector. </PRE></B> The program follows: <B> </B> also possible to declare a local variable as "static", meaning it retains its value from one invocation of the function to the next. For example: <B> </B> This prints:
 * The concept of local and global variables should be clear by now. It is

<B><PRE> 0  2   4   6   8    10   12   14 </PRE></B> -- since the initial value of a integer is 0 by default. It is not a good idea to rely on a default value!

there's little reason to use them: "register", which declares that a variable should be assigned to a CPU register, and "volatile", which tells the compiler that the contents of the variable may change spontaneously.
 * There are two other variable declarations that should be recognized, though

There is more and less than meets the eye to these declarations. The "register" declaration is discretionary: the variable will be loaded into a CPU register if it can, and if not it will be loaded into memory as normal. Since a good optimizing compiler will try to make the best use of CPU registers anyway, this is not in general all that useful a thing to do.

The "volatile" declaration appears ridiculous at first sight, something like one of those "joke" computer commands like "halt and catch fire". Actually, it's used to describe a hardware register that can change independently of program operation, such as the register for a realtime clock.

type conversion will happen transparently. If a "char" is converted to a "short" data type, or an "int" is converted to a "long" data type, for example, the converted data type can easily accommodate any value in the original data type.
 * C is fairly flexible in conversions between data types. In many cases, the

Converting from a bigger to a smaller data type can lead to odd errors. The same is true for conversions between signed and unsigned data types. For this reason, type conversions should be handled carefully, and it is usually preferable to do them explicitly, using a "cast" operation. For example, a cast conversion can be performed from an "int" value to a "float" value as follows: <B> </B>
 * It is possible to define custom "enumerated" types in C. For example:

<B> </B> -- defines enumerated type "day" to consist of the values of the days of the week. In practice, the values are merely text constants associated to a set of consecutive integer values. By default, the set begins at 0 and counts up, so here "saturday" has the value 0, "sunday" has the value 1, and so on. Any set of number assignments can be specified if desired: <B> </B> Obviously much the same could be done with sets of "#define" directives, but this is a much cleaner solution. Once the type is defined, for example, variables of that type can be declared as follows: <B> </B> The variable "today" will act as an "int" variable and will allow the operations valid for "int" variables. Once more, remember that C doesn't do much in the way of bounds checking, and it is not wise to rely on the C compiler to give warnings.

<B> </B> Then variables of this type could be declared as follows: <B> </B>
 * Finally, a "typedef" declaration can be used to define custom data types: