# Laboratory: Types in C

Summary: We explore basics of types in C.

Prerequisites: Familiarity with basic Linux commands. Ability to use an editor. Ability to compile C files.

## Preparation

b. Open a terminal window into which you can type commands.

c. Create a directory for this lab. (I'd suggest something like `~/Courses/CSC161/MoreTypes/`, but it's up to you.)

d. In that directory, create a file called `Makefile` that contains the following line.

```CFLAGS=-Wall
```

## Exercises

### Exercise 1: Coercion

Determine experimentally, what happens when

• You assign a character to an integer.
• You assign an integer to a character.
• When the integer is in the range 0..127
• When the integer is negative.
• When the integer is greater than 256.
• You assign a long to a short.
• Anything else you think might be interesting.

For example, to explore the assignment of a long to a short, you might write

```  long l;
short s;
...
l = SHRT_MAX + 5;
s = l;

printf ("Long: %ld\n", l);
printf ("Short: %d\n", s);
```

### Exercise 2: Enumerated Types

Consider the following code:

```enum values { ALPHA, BETA, GAMMA };

int
main ()
{
int i;
enum values v;

i = BETA;
v = 23;
}
```

a. What do you expect the compiler to do if you attempt to compile this code? (Assume that you're using `-Wall`.

c. What do you expect `splint` to report for this code?

e. What value do you expect `i` to have when you print it out?

### Exercise 3: Incrementing

You've learned that the `++` operation increments its parameter. You've also learned that you can place it before or after a variable. What's the difference? Let's check.

a. Predict the output of the following chunk of code.

```  int x = 5;
printf ("x = %d\n", x);
printf ("x++ = %d\n", x++);
printf ("x = %d\n", x);
printf ("++x = %d\n", ++x);
printf ("x = %d\n", x);
```

c. Predict the output of the following chunk of code.

```  int y = 6;
printf ("%d %d %d %d\n", y++, y++, y++, y++);
```

e. Discuss the meaning of your output.

## History

Tuesday, 1 February 2011 [Samuel A. Rebelsky]

Monday, 7 February 2011 [Samuel A. Rebelsky]

This document may be found at `http://www.cs.grinnell.edu/~rebelsky/Courses/CSC161/2011S/Labs/more-types-lab.html`.
A PDF version of this document may be found at `http://www.cs.grinnell.edu/~rebelsky/Courses/CSC161/2011S/Labs/type-lab.pdf`