Total Pageviews

Monday, November 28, 2011

C loves me...C loves me not...

Hi C Programmers,caught up in another sticky situation. And you gotta help me out in this.Pertains to pointers and all stuff.Hope you come up with a soultion. Long live C.


This program gives an error of "invalid lvalue in increment" in the line with printf()
#include <stdio.h>
main()
{ int p =1;
printf("%d",++p++);

}

But if we modify the program to operate it on a pointer as follows:

#include <stdio.h>
main()
{ int *p,a =1 ;
 p = &a;
printf("%d",++*p++);
}

It runs successfully and prints '2' as output.
What is causing the difference here.Variable 'p' and '*p' are both integers being treated in the same way.The only aberration here  is that if i put *p in parenthesis in the second program like (*p),it gives the same error as in the first program!!Please quote a possible explanation to it

2 comments:

  1. I’m not having the exact answer now, but I guess you can do one operation on a variable at a time. Either a post increment or pre increment.
    So, 1st one fails.

    In 2nd program, you are incrementing the value in ++*p and then the pointer as whole will be incremented to point the next memory address.
    Try this:
    printf ("%d\n", ++*p);
    printf ("%d\n", *p);

    If you add the brackets it’ll be like first program and will fail.

    ReplyDelete
  2. ok..i am pretty convinced about the explanation of the first program...
    and thanks for the 2nd suggestion...!! :)

    ReplyDelete