User Defined Data Types, Part 1
- We have this diagram from chapter 3 of the book
-
- She defines simple types as a data type in which each value is atomic or indivisible.
- An int, 3, can not be broken down any further.
- But a string "bob" has three character components.
- We have looked at most of the simple types
- A few bits she discusses here
- sizeof (type or expression)
- returns the size of the argument in bytes.
- Write a quick demo program.
- limits.h or climits
- INT_MIN, INT_MAX, LONG_MIN, LONG_MAX, ...
- Characters
- Represented internally as an int, two's compliment.
- printed according to the ascii chart. (man ascii)
- User Defined Types, sort of
- Sometimes it is nice to be able to provide your own name to a data type.
- This is probably not as useful here, but this is where she covers it.
- typedef existing_type new_type;
- typedef int number;
- The identifier number
- Can now be used anywhere a type is permitted
- Is now equivalent to the type int
- This is generally done in the global declaration area, before it will be used.
- It is not common to provide a typedef for a simple type, but it can be done.
- Here is a somewhat silly example
- ON the BBC program The Code, they introduce an equation that models population. If n is the current population represented as a percent of the maximum population, and R is a reproduction rate, nnext = R×n×(1-n). This is apparently good when r is about 2. A chaotic system arises when R is closer to 4. Apparently lemmings have a reproduction rate that 3.57, which gives rise to chaos. Write a program which simulates the population of lemmings.
- There is a discussion of this here and a wikipedia page as well.
- I am not sure the type I want to represent the population, float, double or long double, so I will do a typedef float PopulationT
- While it is not a requirement, I find ending a type with a T helps me detect that it is a type and not a constant, function, or variable.
- For expedience I will just hard code the initial population and the value of R.
- Here is one version of the code