Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the diffrence between prefix/postfix and increment operator

#include<stdio.h>
void h (int *p) { *p++; }
int main ( )
{
    int index = 100;
    h(&index);
    printf("%d\n",index);
}

This code gives 100 but the one below gives 101 as output. Are not i+=1 and i++ same thing?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It’s all a matter of operator precedence. The complete list is here.

++ has precendence over * (dereferencing), but * has precedence over +=.

Therefore:
*p++ is actually *(p++),
whereas *p+=1 is (*p)+=1.

This means that in the 1st case the increment is done before dereferencing, and has no effect on the passed int (only on the address in the local parameter p).
In the 2nd case the derefrencing is done first and then the increment is performed on the dereferenced value, i.e. the passed int.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading