Which one is better: Pre-increment or Post increment?
belongs to collection: C interview questions, your interviewer might ask
All Answers
total answers (1)
belongs to collection: C interview questions, your interviewer might ask
total answers (1)
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 the pre-increment operator? The answer to this question is that ‘A’ will be skipped and B will be printed.
Output: B
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.
Output: A
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.
need an explanation for this answer? contact us directly to get an explanation for this answeriLoop = 0.