小编Sux*_*sem的帖子

无符号值之间的减法 - 意外结果

我有两个变量(test1test2),都是无符号的.我需要检查哪一个更大.

我试图了解如果发生溢出会发生什么.

我的第一个测试是使用uint8_t(char)数据类型完成的:

#include <stdio.h>
#include <stdint.h>
#include <math.h>

int main()
{
    uint8_t test1 = 0;
    printf("test1 = %d\n", test1);

    uint8_t test2 = pow(2, 8 * sizeof(test1)) - 1; //max holdable value of uint8_t
    printf("test2 = %d\n", test2);

    uint8_t test3 = test1 - test2;
    printf("test1 - test2 = %d\n", test3);

    if ((test1 - test2) == 0)
        printf("test1 == test2\n");
    if ((test1 - test2) > 0)
        printf("test1 > test2\n");
    if ((test1 - test2) < 0) …
Run Code Online (Sandbox Code Playgroud)

c c++

6
推荐指数
2
解决办法
1425
查看次数

标签 统计

c ×1

c++ ×1