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


Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.