简体   繁体   中英

Loop Structure that Increments variable until it overflows?

This problem for my intro to C coding class states:

Write a program that will determine the biggest positive value that your machine can achieve for each of the following data types. (and thus you can figure out the number of bits used for each of the data types). In order to find the biggest value, use a simple loop structure that increments a variable of that datatype, until it overflows.

It instructs me to do it with multiple data types, such as int , char , short int , etc.

Im not really sure what the question is asking, am I just supposed to make an infinite loop that takes a variable of certain data type, and increase its value every time until it gets so big that the program breaks?? Or is it asking something totally different

Overflow happens when the data is too big to fit in the data type, what it happens is that the value overflows and precision is lost.

Let's suppose that we're working with two bits, so we have this table

00
01
10
11

These are all the numbers values that fit, in two bits. 11 in binary is 3 in decimal, if you increment it you will get 100 , if you truncate this to less significant bits you have, 00 which is 0, and this is the behavior that you're searching.

I will let the implementation as an exercise for you, since this is homework

cheat sheet for the final numerical answers #include <limits.h>

it took much longer than i expect in my practice, and assigning the value of 2^(N) - 10 causes compiler warning.

where N is the number of available bits to store numerical parts of the variable, and by the example from @geckos, by a total bit of 2, 1 for the negative/positive sign, 1 for storing the numerical part, the max signed value would be 1 = (2^1 -1)

so i took the limits.h advantage to shorten the loop times to reach a overflow

finish the actual implementation by yourself though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM