187k views
0 votes
Assume you are programming an embedded microcontroller in C and want your code to follow good software engineering practices, be as portable as possible, and not be wasteful of memory. You need to select a variable that can hold an integer from 0 to 132. What is the best choice for the variable type?

2 Answers

4 votes

Answer:

unsigned char

Step-by-step explanation:

Selecting best data type depends upon the application. Memory and portability are some of the considerations while selecting a data type.

For the given scenario, we need to store an integer in the range of 0 to 132.

Lets have a look at some of the options available for variable data types.

Type: signed char

storage size: 1 byte

Range: -128 to 127

Type: unsigned char

storage size: 1 byte

Range: 0 to 255

Type: int

storage size: 2 byte

Range: -32,768 to 32,767

Unsigned char would be best choice since we need to store only positive integers and it gives us range 0 to 255 which is more than enough for our case and storage size is also least. Other data types are simply too big to consider for this scenario and hence they will be a wasteful of memory.

Please note that the name of data type is "char" but that doesn't mean that we cannot store integer values in it. In-fact in embedded micro-controller environment, char is often used for storing one byte integers.

User Karizma
by
4.5k points
6 votes

Answer:

unsigned char

Step-by-step explanation:

The different data types with their sizes and range are given as follows,

  • char - 1 byte - Value: -128 - 127
  • unsigned char- 1 byte - Value: 0 - 255

All other data types including integers, float, double require 2 bytes or more. Therefore, the data type with the smallest size that can hold values from 0 to 132 is unsigned char.

User Iron Attorney
by
4.6k points