简体   繁体   English

使用溢出和循环在 C 中找到最大值

[英]Find biggest value in C using overflow and loop

The task is to find the biggest int value with a loop.任务是通过循环找到最大的 int 值。 I have the exact same code almost in C and in Java. In Java it works fine, but in C I get the smallest value instead and I would like to know why.我在 C 和 Java 中几乎有完全相同的代码。在 Java 中它工作正常,但在 C 中我得到的是最小值,我想知道为什么。

C C

#include <stdio.h>
int main() {
    int i = 0;
    for (; i+1 > 0; i++) { }
    printf("%d", i);
    return 0;
}

Java Java

public class Java {
    public static void main(String[] args) {
        int i = 0;
        for (; i+1 > 0; i++) { }
        System.out.println(i);
    }
}

Your code seems to falsely assume that in C, an int is guaranteed to wrap to a negative number on overflow .您的代码似乎错误地假设在 C 中,一个int保证在overflow上换行为负数。 This assumption is wrong.这个假设是错误的。 Such a signed integer overflow will invoke undefined behavior in C, so you cannot rely on any specific behavior if you let that happen.这样一个签名的 integer 溢出将调用 C 中的未定义行为,所以如果你让这种情况发生,你不能依赖任何特定的行为。

In order to find the largest representable value of an int , you can use the macro constant INT_MAX , which is defined in limits.h .为了找到int的最大可表示值,您可以使用在limits.h中定义的宏常量INT_MAX

Note however that it is only signed integer overflow that invokes undefined behavior in C. In constrast to that, when using unsigned numbers, they are guaranteed to wrap in a well-defined manner.但请注意,它仅在 C 中调用未定义行为的签名integer 溢出。与此相反,当使用无符号数时,它们保证以明确定义的方式换行。 Therefore, you could find the largest representable unsigned int using your method.因此,您可以使用您的方法找到最大的可表示unsigned int

Also, some compilers have a setting that will cause the behavior of signed integer overflow to become well-defined (assuming that your hardware supports it and uses two's complement for representing signed numbers, which is probably the case).此外,某些编译器的设置会导致有符号 integer 溢出的行为变得明确(假设您的硬件支持它并使用二进制补码表示有符号数,情况可能就是这样)。 In gcc and clang, you can use the -fwrapv compiler command-line option to achieve this.在gcc和clang中,可以使用-fwrapv编译器命令行选项来实现。

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

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