Home » C programming language

Evaluation of statement '*ptr++' in C language



Learn: How the statement '*ptr++' evaluates in C programming language?

The statement *ptr++ has two unary operators, * (asterisk) and ++ (increment operator), here we will learn how this statement will evaluate.

Operator evaluation depends on the operators' associativity and precedence, unary operators ++ -- + - ! ~ * & have same precedence, so here operator evolution will be based on operator associativity.

Associativity of Unary operators are: right to left

Hence, ++ operator will evaluate first then * will be evaluated.

The statement *ptr++ will be evaluate as ptr++ and *ptr.

Consider the following example:

#include <stdio.h>

int main()
{
	int x=20;
	int *ptr=&x;
	
	*ptr++;
	
	printf("%u\n",*ptr);
		
	return 0;
}

The output will be a garbage value, because initially ptr is pointing to the address of x but after ptr++ it will point to the next memory block (Memory address of x + sizeof(int)), that may has some garbage value.

Evaluation of the statement printf("%u\n",*ptr++);

In this statement printf("%u\n",*ptr++); ++ is a post increment operator, that will be evaluate after the execution of printf() statement. So it will print the value of x (because initially ptr is pointing to address of x) after leaving the statement ptr++ will evaluate.

Consider the given program

#include <stdio.h>

int main()
{
	int x=20;
	int *ptr=&x;
	
	printf("%u\n",*ptr++);
		
	return 0;
}

Here, output will be 20






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.