# Type Analysis

CS157 TypeAnalysis

# Dimensional Analysis

My father, a mechanical engineer, taught me that you have to make sure that the dimensions are correct in a calculation, before you worry about getting the numbers right. For example:

• A car going 48 miles/hour, takes how long to go 6 miles?
• 48 divided by 6 is 8, so the answer is 8 hours.

# Let’s Try That Again

Do it again, but with only dimensions:

• miles/hour divided by miles gives 1/hours, or hours-1. Oops!

Getting the numbers out of the way let us focus on the units, on the dimensions.

# Type Analysis

Similarly, in programming, you should perform type analysis to make sure that you got the types right.

```double d;
int x;
d = 12.0/x;
```
 What type is `12.0`? `double` What type is `x`? `int` What type is `12.0/x`? `double` What type is `d`? `double`

Good, `d` and `12.0/x` are the same type (or, at worst, compatible types).

# Type Analysis

```int *p = malloc(sizeof(int));
*p = 1;
```
 What type is `p`? `int *` What type is `*p`? `int` What type is `1`? `int`

Hooray, they match!

# Type Analysis

```int *q;
q = 1;
```
 What type is `q`? `int *` What type is `1`? `int`

That’s no good—you can't assign an `int` to an `int *`.

# Type Analysis

```struct Date { int m, d, y; } info[20];
short chris = 1492;
info[10].y = chris;
```
 What type is `info`? array of `struct Date` What type is `info[10]`? `struct Date` What type is `info[10].y`? `int` What type is `chris`? `short`

They’re not the same type, but they’re compatible types (you can assign a `short` to an `int`) and that’s good enough.

# Type Analysis

```char name[] = "Jack Applin";
strcpy(name+5, "Smith");
```
 What type is `name`? array of `char`, or `char *` What type is `name+5`? `char *` What type is `"Smith"`? array of `const char`, or `const char *` What type is `strcpy`’s 1st argument? `char *` What type is `strcpy`’s 2nd argument? `const char *`

Perfect!

# Type Analysis

```struct Date { int m, d, y; };
struct Date *p = malloc(sizeof(struct Date) * 9);
struct Date *q = p;
(q++)->y = 1969;
```
 What type is `q`? `struct Date *` What type is `q++`? `struct Date *` What type is `(q++)->y`? `int` What type is `1969`? `int`

Great!

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2017-12-19T11:20

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA