Efficient coding technique with pointers
When we use pointers in C++, more precisely when we use them as index variables in a for loop to traverse an array, there are two ways to move to the next position: p++ (post-increment) and ++p (pre-increment). At first sight they look almost identical, but in reality there is an important difference between them.
With p++, the program makes a copy of the pointer, - which in case of complex stuctures call an init method which could cause side-effects - and then increment the old value. By using ++p, the program first increases the pointer and then returns the new value. This leads to the conclusion that, when trying to optimize code, using ++p is more practical and efficient. At first glance, in simple programs, the difference may not be visible, but in large loops this trick can save both time and memory.
An example:
for (int *p = v; p < v + n; ++p) {
cout << *p << " ";
}
for (int *p = v; p < v + n; p++) {
cout << *p << " ";
}
Comentarii
Trimiteți un comentariu