简体   繁体   English

这些数据类型之间有什么区别?

[英]What is the difference between these data types?

In C++, what is the difference between short int, unsigned int, signed int, and int? 在C ++中,short int,unsigned int,signed int和int有什么区别? What are there applications? 有哪些应用程序? When do you use short int, unsigned int, etc. ? 什么时候使用short int,unsigned int等?

Take a look! 看一看! You tell me! 你告诉我!

#include <iostream>
#include <cstdlib>
#include <limits>
using namespace std;

int main(){

    cout << "min_int = " << numeric_limits<int>::min() << endl;
    cout << "max_int = " << numeric_limits<int>::max() << endl;

    cout << "min_unsigned_int = " << numeric_limits<unsigned int>::min() << endl;
    cout << "max_unsigned_int = " << numeric_limits<unsigned int>::max() << endl;

    cout << "min_short = " << numeric_limits<short>::min() << endl;
    cout << "max_short = " << numeric_limits<short>::max() << endl;

    cout << "min_unsigned_short = " << numeric_limits<unsigned short>::min() << endl;
    cout << "max_unsigned_short = " << numeric_limits<unsigned short>::max() << endl;

    return EXIT_SUCCESS;
}

In most cases int is what you want, if you are going to be strictly working with non negative numbers unsigned is good. 在大多数情况下,int是您想要的,如果要严格使用非负数unsigned是好的。 But often standard library function return negative values for errors. 但是标准库函数通常会为错误返回负值。

Short is primarily used for small values in larger data structures as a memory optimization, or for interfacing with network or file formats. Short主要用于较大数据结构中的较小值,以进行内存优化,或者用于与网络或文件格式进行接口。

If you want to create a function that accepts only positive numbers, which might be done to restrict others from passing it negative values or from freeing your function from having to check the sign of the values passed, you could use an unsigned int. 如果要创建一个仅接受正数的函数,可以这样做以限制其他人传递负数或使函数不必检查传递的值的符号,则可以使用unsigned int。 Of course this doesn't stop anybody from casting a negative int to an unsigned int. 当然,这不会阻止任何人将负整数转换为无符号整数。 This will just results in your function interpreting it as a huge number (since the most significant bit will be 1 to represent the previously negative number) but then that's the fault of the person casting that value. 这只会导致您的函数将其解释为一个巨大的数字(因为最高有效位将为1代表以前的负数),但是那是该类型的人的错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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