Tuesday, September 12, 2017

Difference between *p++, *++p and ++*p

One of the most common question is which version of *p++, *++p or *p++ to use while programming.

There is no right answer and the answer varies from the usage point of view. Understanding the output of each form would help you in deciding which one should be used.

There are two simple rules to remember related to postfix, prefix and de-reference operator.

1. Precedence of postfix is higher than both prefix and de-reference operator. Associativity of postfix operator is left to right.

2. Precedence of prefix and de-reference operator is same. Associativity is right to left.

Let's try to understand the results based on these rules by below examples -

int a[] = {5, 10};
int *p = a;

*p++
Result - 10
The precedence of p++ is higher so pointer is incremented first and then de-referenced.

*++p
Result - 10
The associativity is right to left so pointer is incremented first and then de-referenced.

++*p
Result -6
The associativity is right to left so pointer is de-referenced first then incremented.

Please leave your comments with suggestions/feedback.

Thursday, April 27, 2017

memcpy vs strcpy

The functions which begins with "mem" prefix also operate on characters but, they do not use the null terminator convention.

This is the reason they will always need the size of characters to operate on.

For example, when using memcpy it requires size as well, though, strcpy only needs dest and src pointers. It can automatically detect end of string using null character.

void *memcpy(void *dest, const void *src, size_t n);
 
char *strcpy(char *dest, const char *src); 

Monday, April 24, 2017

What is Smart Pointer

Smart pointer is a class which wraps raw C++ pointers with some additional functionality, e.g. automatic memory de-allocation, reference counting etc.

Smart pointers should be preferred over raw pointers because it could help in overcoming some limitation of raw pointers such as memory leak, dangling pointers etc.