-2

I am reading Understanding Pointers in c.

I found one program here it is.

#include<Stdio.h>
#include<conio.h>
int main()
{
    static int arr[]={97,98,99,100,101,102,103,104};
    int *ptr=arr+1;
    printf("\nThe base Address is:%u\n",arr);
    print(++ptr,ptr--,ptr,ptr++,++ptr);
    return getch();
}

print(int *a,int *b,int *c,int *d,int *e)
{
      printf("%d  %d  %d  %d  %d",*a,*b,*c,*d,*e);
}

The program is perfect what i think is that it must generate following output: 99 99 98 98 100. But it gives following output: 100 100 100 99 99

I am unable to understand help me to understand it.

Nirav Kamani
  • 3,192
  • 7
  • 39
  • 68

2 Answers2

4

In addition to the order of evaluation of function parameters being unspecified, the program sports several items with undefined behavior:

  • It tries to access the value of an expression with side effects before reaching the next sequence point (it does that several times in the call of print), and
  • It tries printing a pointer using %u format specifier.

The way the program is written it can print anything at all, not print anything, or even crash: that's the consequences of having undefined behavior.

If you want the evaluation of parameters to be in a specific order, introduce temporary variables, and do evaluation sequentially, like this:

#include<stdio.h>
#include<conio.h>
int main()
{
    static int arr[]={97,98,99,100,101,102,103,104};
    int *ptr=arr+1;
    printf("\nThe base Address is:%p\n",(void*)arr);
    int *tmp0 = ++ptr;
    int *tmp1 = ptr--;
    int *tmp2 = ptr;
    int *tmp3 = ptr++;
    int *tmp4 = ++ptr;
    print(tmp0, tmp1, tmp2, tmp3, tmp4);
    return getch();
}
print(int *a,int *b,int *c,int *d,int *e)
{
      printf("%d  %d  %d  %d  %d",*a,*b,*c,*d,*e);
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2
print(++ptr,ptr--,ptr,ptr++,++ptr);

is undefined behaviour because the order in which the parameters are evaluated is not specified by the C standard.

This isn't my real name
  • 4,869
  • 3
  • 17
  • 30
Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33