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 logic here for post increment?

#include<stdio.h>

int main()
{
    int x;
    int *ptr;
    ptr = &x;
    *ptr = 0;
    printf("x= %d\n", x);
    printf("*ptr= %d\n", *ptr);

    *ptr += 5;
    printf("x= %d\n", x);
    printf("*ptr= %d\n", *ptr);
 
    (*ptr)++;
    printf("x= %d\n", x);
    printf("*ptr= %d\n", *ptr);

    return 0;
}

Acc. to precedence brackets will be first simplified and then ++ and therefore it will be post increment :
(*ptr)++ (third portion of question)

value should be 5 as it is post increment operator i.e it will first assign the value and then increment..In this case also it should first assign value and then increment..But answer coming is
6

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

>Solution :

(*ptr)++; // increment the value (to 6)
// other stuff
printf( .... // print the value

The (post)-increment occurs substantially before the value is fetched to be printed.

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