简体   繁体   中英

Why are the results of these two expressions different?

I was developing an answer to another question, and ran into a brick-wall explaining the result computed by GCC on a particular expression. (My answer was related to inline functions; originally the code consisted of two source files and a header. I've concatenated them into a single source file, not using inline .)

Code

//static inline int somename(int x, int y) { return x + y + 1; }
static int somename(int x, int y) { return x + y + 1; }
extern int nothername(int x, int y);

#include <stdio.h>

int main(void)
{
    printf("somename(1,2)   = %d\n", somename(1, 2));
    printf("nothername(2,1) = %d\n", nothername(2, 1));
    return 0;
}

int nothername(int x, int y)
{
    printf("x = %d, y = %d, somename(x, y) = %d, cn = %d\n",
           x, y, somename(x, y),  ((y != 0) ? x / y : x));
    int z1 = somename(x, y) +  (y != 0) ? x / y : x;
    int z2 = somename(x, y) + ((y != 0) ? x / y : x);
    printf("z1 = %d, z2 = %d\n", z1, z2);
    return somename(x, y) + (y != 0) ? x / y : x;
}

Expected output

somename(1,2)   = 4
x = 2, y = 1, somename(x, y) = 4, cn = 2
z1 = 6, z2 = 6
nothername(2,1) = 6

Actual output

somename(1,2)   = 4
x = 2, y = 1, somename(x, y) = 4, cn = 2
z1 = 2, z2 = 6
nothername(2,1) = 2

Question:

  • Why is z1 not 6?

Environment

This is running on MacOS X 10.6.7. I've used GCC 4.2.1 provided by Apple as part of XCode 3; I've used GCC 4.6.0 which I compiled. The original experimentation was related to inline functions in C++; equivalent code using cout etc produces the same computational results. I did check that somename(2, 1) and somename(1, 2) both produce 4.

The precedence of ?: is very low, so

int z1 = somename(x, y) + (y != 0) ? x / y : x;

is interpreted like

int z1 = (somename(x, y) + (y != 0)) ? (x / y) : (x);

which is (4 + 1) ? (2 / 1) : 2 (4 + 1) ? (2 / 1) : 2 , which is 2.

This also explains why adding the parentheses in your computation of z2 fixed the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM