How a pointer increment compares with an increase in index in C

consider the following two codes:

void PrintLetter(char *src) { while(*src != '\0') { printf("%c",*src); src++; } } 

and

 void PrintLetter(char *src) { int i; for(i=0;src[i];i++) printf("%c",src[i]); } 

Is there a performance difference between the two?

+4
source share
2 answers

Nothing. The compiler will perform its optimizations regardless of the form you are writing. The main assembly code is the same.

+5
source

Any performance difference will depend on the compiler.

Some small embedded systems have rather simplified compilers that can create slightly different code for one than the other, but without testing it is difficult to guess what might turn out to be โ€œbetterโ€ (although if I had to guess โ€œblindlyโ€, I would choose the first one) .

With compilers on typical desktop / server systems (e.g. gcc, VC ++, EDG) you are likely to get the same results anyway, so choosing between them is just a matter of choosing what you find more readable.

+2
source

All Articles