Design a computer programming experiment in C++ to determine what happens when
a variable of type int is incremented above its range or decremented below its range. Repeat your experiment to determine what happens with a short int and long int. Next, modify your experiment to find out how unsigned variants of the integer types behave when their range is exceeded. Finally, try your experiment with a float and double.
He just wants you to create a variable of type int, and set it to its max. From there, increment it above that, and display the result. Repeat with going lower than the minimum. From there, do it with short, long, double, float, and unsigned variants of each.
> Design a computer programming experiment in C++ to determine what happens when
> a variable of type int is incremented above its range or decremented below its range.
> Repeat your experiment to determine what happens with a short int and long int.
What happens is undefined behaviour. Technically, anything can happen; different things may happen if you compile with different options; different things may happen with different compilers; different things can happen each time you run the program etc. Experiment? Only if we use the term in a very loose sense.
> find out how unsigned variants of the integer types behave when their range is exceeded.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <limits>
int main()
{
// increment an unsigned int beyond its range
unsignedint a = std::numeric_limits<unsignedint>::max() ;
std::cout << a << '\n' ;
++a ;
std::cout << a << '\n' ;
// decrement an unsigned int beyond its range
a = std::numeric_limits<unsignedint>::min() ;
std::cout << a << '\n' ;
--a ;
std::cout << a << '\n' ;
}
> I have to write a three to five page paper on this question after I write the code,
> so how would I do this without having to include header files like #include <limits>.
> He is wanting me to hardcode it
For an unsigned integral type, 0 is the minimum and -1U converted to the unsigned type would be the maximum.
For a floating point type, without <limits>? Does he expect you to play around with +inf and -inf.
#include <iostream>
#include <limits>
int main()
{
{
// increment an unsigned int beyond its range
unsignedint a = -1U ;
std::cout << a << '\n' ;
++a ;
std::cout << a << '\n' ;
// decrement an unsigned int beyond its range
a = 0 ;
std::cout << a << '\n' ;
--a ;
std::cout << a << '\n' ;
}
{
// increment a double beyond its range
double a = +1.0 / 0.0 ; // +inf
std::cout << a << '\n' ;
a += 0.12345 ;
std::cout << a << '\n' ;
// decrement a double beyond its range
a = -1.0 / 0.0 ; // -inf
std::cout << a << '\n' ;
a -= 0.12345;
std::cout << a << '\n' ;
}
// etc.
}
Im just a beginner, He wont let me turn all of this in like that. He probably understands it but it has to be what we have gone over yet and he hasn't gone over this yet