[xpost] a new C/C++ type that when overflow i see it

Discussion in 'C Programming' started by ¬a\\/b, Aug 9, 2007.

  1. Btw, 20.6b to which refers 14.3 is wrong:
    -----8<-----
    For example, here is a ``careful'' addition function:
    int
    chkadd(int a, int b)
    {
    if(INT_MAX - b < a) {
    fputs("int overflow\n", stderr);
    return INT_MAX;
    }
    return a + b;
    }
    -----8<-----
    How about b = -1, a = INT_MIN being inputs of this "carefully" adding
    function?
    The above looks like the implementation for unsigned addends that was
    turned into signed addition w/o much or any thinking by simply
    changing unsigned int's to int's and UINT_MAX to INT_MAX. The correct
    implementation would be:

    if (b >= 0)
    {
    if (INT_MAX - b < a)) {
    fputs("int overflow\n", stderr);
    return INT_MAX;
    }
    }
    else
    {
    if (INT_MIN - b > a)) {
    fputs("int overflow\n", stderr);
    return INT_MIN;
    }
    }
    return a + b;

    Alex
     
    Alexei A. Frounze, Aug 12, 2007
    #41
    1. Advertisements

  2. ¬a\\/b

    ¬a\\/b Guest

    it seems yes; i need to define a function for each type or explicity
    say what function to call using cast
     
    ¬a\\/b, Aug 13, 2007
    #42
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.