Sum of positive values in an array gives negative result in a c program

后端 未结 4 1556
渐次进展
渐次进展 2021-01-26 10:16

I have a problem that is, when I sum the values of an array (that are all positive, I verified by printing the values of the array), I end up with a negative value. My code for

4条回答
  •  礼貌的吻别
    2021-01-26 10:29

    You are invoking undefined behaviour.

    As integer variables can only hold a limited range of values, going beyond this range is undefined by the standard. Basically anything can happen. In your (and the most common) case, it simply wraps around its binary representation. As this is used for negative values, you will read this as such.

    To circomvent this, use a type for summcp which can hold all possible values. An alternative would be to check if the next addition will overflow by:

    if ( summcp >= INT_MAX - mcp[k] ) {
        // handle positive overflow
    }
    

    Note that the above only works for mcp[k] >= 0 and positive overflow. The other 3 cases have to be handled differently. It is in general best, faster and much easier to use a large enough type for the sum and test lateron for overflow, if required.

    Do not feel tempted to add and test the result!. As integer overflow is undefined behaviour, this will not work for all architectures.

提交回复
热议问题