
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between ++p, p++, and ++p in C
Pointer Airthmetics
In C programming language, *p represents the value stored in a pointer. ++ is increment operator used in prefix and postfix expressions. * is dereference operator. Precedence of prefix ++ and * is same and both are right to left associative. Precedence of postfix ++ is higher than both prefix ++ and * and is left to right associative. See the below example to understand the difference between ++*p, *p++ and *++p.
Example (C)
#include <stdio.h> int main() { int arr[] = {20, 30, 40}; int *p = arr; int q; //value of p (20) incremented by 1 //and returned q = ++*p; printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d
", arr[0], arr[1], *p, q); //value of p (20) is returned //pointer incremented by 1 q = *p++; printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d
", arr[0], arr[1], *p, q); //pointer incremented by 1 //value returned q = *++p; printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d
", arr[0], arr[1], *p, q); return 0; }
Output
arr[0] = 21, arr[1] = 30, *p = 21, q = 21 arr[0] = 21, arr[1] = 30, *p = 30, q = 21 arr[0] = 21, arr[1] = 30, *p = 40, q = 40
Advertisements