简体   繁体   中英

C++ create an integer variable with the largest integer value supported

I was given an assignment and in the question there was this line:

  • min: an int to keep track of the minimum value of the numbers seen so far. Initially min should be the largest integer value supported (do not hard code this value).

I made sure to write unsigned before int minimum; so it's positive. When I print the value of the uninitialized minimum variable, I get 3435973836 . Is that the "largest integer value supported"? The output given by my instructor shows that it's 2147483647 . Am I supposed to do anything extra, or is this value random on each computer?

The largest value that can be stored in an integer depends on the type as well as on your system, and so it may be different from the largest possible value on your instructor's system.

The correct way to get the largest possible value of a numeric type on your system is to use std::numeric_limits . For example:

#include <iostream>
#include <limits>

int main() {
    std::cout << "The largest value an unsigned int can hold is "
        << std::numeric_limits<unsigned int>::max()
        << " and the smallest value is "
        << std::numeric_limits<unsigned int>::min()
        << std::endl;
    return 0;
}

Output:

The largest value an unsigned int can hold is 4294967295 and the smallest value is 0

Live Demo

Note that reading from an uninitialized variable is Undefined Behaviour, which is always wrong and should never be relied on.

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