在C中找到一个简短的int变量的最大值 [英] Finding maximum value of a short int variable in C

查看:185
本文介绍了在C中找到一个简短的int变量的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究K& R的练习2-1,目标是计算不同变量类型的范围,下面是我计算short int可以包含的最大值的功能:

I was working on Exercise 2-1 of K&R, the goal is to calculate the range of different variable types, bellow is my function to calculate the maximum value a short int can contain:

short int max_short(void) {
    short int i = 1, j = 0, k = 0;
    while (i > k) {
        k = i;
        if (((short int)2 * i) > (short int)0)
            i *= 2;
        else {
            j = i;
            while (i + j <= (short int)0)
                j /= 2;
            i += j;
        }
    }
    return i;
}

我的问题是此函数返回的值是:-32768这显然是错误的,因为我期望一个正值.我不知道问题出在哪里,我使用了相同的函数(变量类型有所变化)来计算int可以包含的最大值,并且可以正常工作...

My problem is that the returned value by this function is: -32768 which is obviously wrong since I'm expecting a positive value. I can't figure out where the problem is, I used the same function (with changes in the variables types) to calculate the maximum value an int can contain and it worked...

尽管问题可能是由于ifwhile语句之间的比较引起的,所以进行了类型转换,但这无济于事...

I though the problem could be caused by comparison inside the if and while statements, hence the typecasting but that didn't help...

任何主意是什么原因造成的?预先感谢!

Any ideas what is causing this ? Thanks in advance!

编辑:感谢Antti Haapala的解释,符号位的溢出导致未定义的行为,而不是负值.

Thanks to Antti Haapala for his explanations, the overflow to the sign bit results in undefined behavior NOT in negative values.

推荐答案

您不能使用像这样的计算来推断有符号整数的范围,因为有符号整数溢出具有未定义的行为,最好是缩小转换范围会导致实现定义的值或信号升高.正确的解决方案是只使用<limits.h>SHRT_MAXINT_MAX....通过算术推导有符号整数的最大值是标准化C语言中的一个棘手问题,并且自1989年第一个标准发布以来就如此.

You can't use calculations like this to deduce the range of signed integers, because signed integer overflow has undefined behaviour, and narrowing conversion at best results in an implementation-defined value, or a signal being raised. The proper solution is to just use SHRT_MAX, INT_MAX ... of <limits.h>. Deducing the maximum value of signed integers via arithmetic is a trick question in standardized C language, and has been so ever since the first standard was published in 1989.

请注意,K& R的原始版本比C的标准化早了 11 年,甚至还早于第2 个版本-"ANSI-C"版本早于最终标准,并且与最终标准有所不同-它们是为与现在的C语言几乎(但不是完全)完全不同的语言编写的.

Note that the original edition of K&R predates the standardization of C by 11 years, and even the 2nd one - the "ANSI-C" version predates the finalized standard and differs from it somewhat - they were written for a language that wasn't almost, but not quite, entirely unlike the C language of this day.

不过,您可以轻松地对无符号整数执行此操作:

You can do it easily for unsigned integers though:

unsigned int i = -1;
// i now holds the maximum value of `unsigned int`.

这篇关于在C中找到一个简短的int变量的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆