Q:

Which one is better: Pre-increment or Post increment?

0

Which one is better: Pre-increment or Post increment?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

Nowadays compiler is enough smart, they optimize the code as per the requirements. The post and pre-increment both have their own importance we need to use them as per the requirements.

If you are reading a flash memory byte by bytes through the character pointer then here you have to use the post-increment, either you will skip the first byte of the data. Because we already know that in the case of pre-increment pointing address will be increment first and after that, you will read the value.

Let’s take an example of the better understanding,
In the below example code, I am creating a character array and using the character pointer I want to read the value of the array. But what will happen if I used a pre-increment operator? The answer to this question is that ‘A’ will be skipped and B will be printed.

#include <stdio.h>
int main(void)
{
    char acData[5] = {'A','B','C','D','E'};
    char *pcData = NULL;
    pcData = acData;
    printf("%c ",*++pcData);
    return 0;
}

But in place of pre-increment if we use post-increment then the problem is getting solved and you will get A as the output.

#include <stdio.h>
int main(void)
{
    char acData[5] = {'A','B','C','D','E'};
    char *pcData = NULL;
    pcData = acData;
    printf("%c ",*pcData++);
    return 0;
}

Besides that, when we need a loop or just only need to increment the operand then pre-increment is far better than post-increment because in case of post increment compiler may have created a copy of old data which takes extra time. This is not 100% true because nowadays the compiler is so smart and they are optimizing the code in a way that makes no difference between pre and post-increment. So it is my advice, if post-increment is not necessary then you have to use the pre-increment.

Note: Generally post-increment is used with array subscript and pointers to read the data, otherwise if not necessary then use pre in place of post-increment. Some compiler also mentioned that to avoid to use post-increment in looping condition.

while (a[iLoop ++] != 0)
{
// Body statements
}


iLoop = 0.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Embedded C interview questions and answers (2022)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How will you protect a pointer by some accidental ... >>
<< What are the post-increment and decrement operator...