What type for subtracting 2 size_t's?

后端 未结 4 1561
花落未央
花落未央 2020-12-30 00:46

Which type in C should be used to represent the difference between two objects\' sizes?

As size_t is unsigned, something like

size_t dif         


        
4条回答
  •  时光取名叫无心
    2020-12-30 01:37

    When I am really worried about overflow issues like that (especially when working in modular arithmetic where "negative" values wrap somewhere other than ~0) I just split it into two cases:

    if (a > b) {
        size_t diff = a - b;
    } else {
        size_t diff = b - a;
        // code here subtracts diff rather than adds it, etc.
    }
    

提交回复
热议问题