1
#include<conio.h> 
#include<stdio.h>

void fun(int []);

int main(){

int arr[10] = {1,1,1,1,1};
int i=0;
printf("Before Change : ");
for( i=0;i<5;i++){
     printf("%d, ",arr[i]);
}

fun(arr);

printf("\nAfter Change : ");
for( i=0;i<5;i++){
     printf("%d, ",arr[i]);
}
getch();
}

void fun(int a[])
{
 int i;
 for(i=0;i<5;i++){

         //a[i] = a[i]++; // Comment 1
         //a[i] = ++a[i]; // Comment 2
 }
 }

When I use Comment 1 Statement then I Get this output:

Before Change : 1, 1, 1, 1, 1,

After Change : 1, 1, 1, 1, 1,

When I use Comment 2 Statement then I Get this output:

Before Change : 1, 1, 1, 1, 1,

After Change : 2, 2, 2, 2, 2,

Here I know that why Comment 2 Statement get array Change Due to pre increment. But my question is Why Comment 1 Statement not able to Change array elements, since changes made in other function (here is fun()) is able to effect same changes in same array.

So Why array elements do not change in comment 1 statement?

AnshulJS
  • 308
  • 3
  • 10
  • 2
    Both of those are undefined behavior. If you want to increment the elements of the array, then just write `a[i]++;`. End of story. – user3386109 Apr 12 '15 at 05:59
  • post increment--> say a= 5 ; b = a++; then value of b is 5 and after that a value will increase to 6. pre increment --> b = ++a; first value of a will increase to 6 and then it got assigned to b. – rabi shaw Apr 12 '15 at 06:01

1 Answers1

1
a[i] = a[i]++;

and

a[i] = ++a[i];

both have undefined behavior, and should not be used.

If you want to increment, you should always do one of the following:

a[i] = a[i] + 1;
a[i] += 1;
a[i]++;
AndrewGrant
  • 786
  • 7
  • 17