Home > front end >  C data types and memory storage of characters?
C data types and memory storage of characters?

Time:11-01

Hi can anybody solve this exercise from King, this is one thing that I cannot wrap my head around in C. I understand data types in C and their space they are capable of holding. At least I think I did, but for whatever reason I cannot understand the answer to the exercises. This is not some homework request, this is just so I can understand C data types better, and it is something that has plaque me for a while already.Can somebody explain to me the answer and steps involve in getting to them. I have tried many things re-read the chapter search online. I cannot wrap my head around this. Thank you.

Exercise 7.06 For each of the following items of data, specify which one of the types char, short, int, or long is the smallest one guaranteed to be large enough to store the item.

(a) Days in a month

(b) Days in a year

(c) Minutes in a day

(d) Seconds in a day

Solution

(a) Max. 31: char

(b) Max. 366: short

(c) Max. 1500: short

(d) Max. 86760: long

CodePudding user response:

C implementations may use different widths for their integer types, but the C standard guarantees certain minimums. These are specified in C 2018 5.2.4.2.1 1 (the 2018 C standard, clause 5.2.4.2.1, paragraph 1).

(a) Days in a month

There are up to 31 days in a month. char is guaranteed to store up to at least 127, so it is sufficient.

(b) Days in a year

There are up to 366 days in a year. That is more than char is guaranteed to store, so it is insufficient. short is guaranteed to store up to 32,767, so it is sufficient.

(c) Minutes in a day

There are 60•24 = 1,440 minutes in a regular day, or perhaps 60•25 = 1,500 if there is a transition between Daylight Savings Time and Standard Time that we are including. Again char is insufficient and short is sufficient.

(d) Seconds in a day

There are 60•60•24 = 86,400 seconds in a regular day, perhaps 60•60•25 = 90,000 if there is a transition we are including, and one more if there is a leap second, so that gives up to 90,001. That is more than short is guaranteed to store, so it is insufficient. int is also only guaranteed to store up to 32,767, so it is insufficient. long is guaranteed to store up to 2,147,483,647, so it is sufficient.

CodePudding user response:

The range of any two'd complement signed binary data type is: -2N-1 to -2N-1-1. Where N is bit-width of the data type.

The standard specifies minimum widths for each if these types of 8, 16, 16 and 32 for each if char, short, int and long respectively. Each may be wider, but not wider than the next type in that order, or narrower than the preceding type.

  • Related