-4

I can't understand the answer to the following question. Please help me :)

what is the output:

struct INT
{
    int i;
};

typedef struct INT INT;

int Change(INT** INTptr)
{
    (*INTptr) = (INT*)malloc(sizeof(INT));
    (*INTptr)->i = 1000;
    return 500;
}

int main()
{
    INT dummy = {750};

    INT* ptr = &dummy;

    ptr->i = Change(&ptr);

    printf("dummy.i = %d, ptr->i = %d\n", dummy.i, ptr->i);

    return 0;
}

Got this from a friend of mine.

I thought the answer would be:

dummy.i = 750, ptr->i = 500

but when I run the code (GCC compiler) I get:

dummy.i = 500, ptr->i = 1000

can it be my answer with a different compiler?

Moreover, I still don't understand why the output is 500 and 1000...

thanks in advance!

Rotem
  • 21,452
  • 6
  • 62
  • 109
barbur
  • 19
  • 2
    http://i.qkme.me/3ufkkc.jpg –  Jun 04 '13 at 12:23
  • At a guess, compiler figured that `ptr = &dummy`, generated code as `dummy.i = ...` – Hasturkun Jun 04 '13 at 12:25
  • 1
    Why all the down votes? I don't have time to answer it right now but the poster had a hypothesis, did the experiment, doesn't understand the results, and now has specific questions. –  Jun 04 '13 at 12:26
  • 2
    Related: http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points – Hasturkun Jun 04 '13 at 12:28
  • 2
    @barbur Just to clear up a misunderstanding, I was agreeing with you above. I really would like to answer this but I have to go. I upvoted the question to offset the downvotes. This is a legitimate question, I was asking why everyone was downvoting it (I think we posted earlier at the same time.) –  Jun 04 '13 at 12:34
  • @wilsonmichaelpatrick, oh... this is embarrassing! My most sincere apologies for you! – barbur Jun 04 '13 at 12:39
  • 1
    In what way is this question "too localized"? Can the people who voted to close comment on this, because I think this meets the "good fit" criteria of "a specific programming problem", "a software algorithm", "software tools commonly used by programmers", and "practical, answerable problems that are unique to the programming profession"? I genuinely don't understand. –  Jun 04 '13 at 12:41
  • @wilsonmichaelpatrick It's too localized because there's one person ever who will find it useful (that's barbur), and he also didn't show any research effort to get the answer himself. –  Jun 04 '13 at 12:56

1 Answers1

1

sequence point is the magic word here. and

ptr->i = Change(&ptr);

is the position. (by whom will ptr be changed? by the Assignment or by the function via the call by reference)

Peter Miehle
  • 5,984
  • 2
  • 38
  • 55
  • Thanks! so, the answer here is actually undefined behaviour? can I get from different compilers different results? – barbur Jun 04 '13 at 12:40
  • 1
    Visual studio and GCC evaluate this differently. VS apparently works out where it is going to store `ptr->i` before the call to `Change()` alters ptr, and gcc does it after. – Bull Jun 04 '13 at 13:08