Explore BrainMass
Share

Explore BrainMass

    Macro processing in C/C++

    This content was COPIED from BrainMass.com - View the original, and get the already-completed solution here!

    The following code fragment produces the correct result sometimes and sometimes it does not. Explain what is happening and why.

    #include <stdio.h>
    #define max(a,b) ((a) > (b) ? (a): (b))
    void main(void)
    {
    int i = 0;
    int j = 0;
    int a = 3;
    int b = 4;
    int c = 6;
    int d = 5;
    i = max(a,b);
    j = max(c,d);
    printf("i = %i, j = %in",i,j);
    i = max(a++, b++);
    printf("a = %i, b = %in",a,b);
    j = max(c++,d++);
    printf("c = %i, d=%in",c,d);
    return;
    }

    © BrainMass Inc. brainmass.com October 10, 2019, 4:35 am ad1c9bdddf
    https://brainmass.com/computer-science/c/macro-processing-in-c-c-468303

    Solution Preview

    Given code fragment will produce unexpected results in case of

    i = max(a++, b++);

    and

    j = max(c++,d++);

    Things would have worked as expected if max(...) were a function call. However it is a macro call, and thus given code fragments become following after preprocessing step during compilation.

    i = ((a++) > (b++) ? (a++) : (b++));

    and

    j = ((c++) > (d++) ? (c++) : (d++));

    Before these code fragments execute,
    (a,b) : (3,4)
    (c,d) : ...

    Solution Summary

    Response first points out the code fragments that will produce unexpected results, and then goes on explaining in complete detail (and step-by-step manner), why it is so.

    $2.19