簡體   English   中英

將無符號變量的差異存儲到有符號變量中

[英]Storing difference of unsigned variables into signed variables

將兩個無符號整數變量的差存儲到有符號整數變量中是否有任何潛在的問題?

考慮下面的示例:

#include <stdio.h>

int main()
{
    unsigned int a, b, d1;
    signed int d2;

    a = 20;
    b = 200;

    d1 = a - b; 
    d2 = a - b; // Line 1

    printf("d1 = %u\n", d1);
    printf("d2 = %d\n", d2);

    return 0;

}

如果在程序的后面使用帶符號的變量,是否有任何潛在的問題?

是的,您可能會溢出。

2個無符號整數的差可以和無符號整數一樣大,並且不適合(相同類型的)有符號整數[除非要換成負數,但很確定您不希望這樣做] 。

您可以使用測試案例輕松驗證:

a = unsigned Int max;
b = 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM