2

Possible Duplicates:
C programming: is this undefined behavior?
Is this program having any sequence point issues ?

Hi,

I am running the following program

void print(int *a, int *b, int *c, int *d, int *e)
{

    printf("\n %d %d %d %d %d",*a,*b,*c,*d,*e);
}

int _tmain(int argc, _TCHAR* argv[])
{

    static int arr[] = {97,98,99,100,101,102,103,104};
    int *ptr=arr+1;
    print(++ptr,ptr--,ptr,ptr++,++ptr);
    getchar();
    return 0;
}

I thought I would be getting 99 99 98 98 100 as output but I am getting 100 100 100 99 100 as output. I cant understand why. Do pointers behave differently then normal variable when used with ++ or --(pre or postfix) operators. Can u please help me understand how the program is working

Community
  • 1
  • 1
Sudeep Gill
  • 193
  • 1
  • 2
  • 6

1 Answers1

4

You're reading and modifying ptr multiple times without a sequence point. This is undefined behavior. The compiler can emit any code it feels like. Don't do it.

Please note also that the order of evaluation of function arguments is not defined, so your print statement, even if it was well-defined, would not necessarily output what you think it would.

See this question Is this undefined behavior for a similar issue.

Community
  • 1
  • 1
Mat
  • 202,337
  • 40
  • 393
  • 406