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






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.