210 views
1 votes
1 votes
#include<stdio.h>
void foo(int*);
int main()
{
    int x=30,*a=&x;
    foo(a++);
}
void foo(int* a)
{
    printf("%d\n",*a);
}

this program gives output=30;

_____

#include<stdio.h>
void foo(int*);
int main()
{
    int x=30;
    foo((&x)++);
}
void foo(int* a)
{
    printf("%d\n",*a);
}

But this is giving compiler error  

Why?

1 Answer

Best answer
1 votes
1 votes

There is a subtle difference between the two code . 

For this we have to understand one thing :

When we declare a variable , it is associated with an address and memory is allocated to it in compile - time . So when we try to change the address of the variable , it is not possible because address bounds to remain same as memory is allocated at compile time. So we cannot manipulate the address

Hence the compiler error "L-value required" is displayed.So to overcome this , if at all we want to access manipulated memory location , then we use pointer variable corresponding to the original variable as has been done in the first code snippet.

Also the operation in the function call is post increment , so first the original value of address is used as an argument and thereafter the pointer is incremented ..

So when we go to the function and dereference it , we get the value as 30 . If however we were used pre increment operator , then we would have got garbage value.

I hope this clears the distinction betweent the two.

selected by

Related questions

0 votes
0 votes
0 answers
1
Nils asked Nov 30, 2017
222 views
can null graph can be biparted graph ?