Search code examples
cloopsfor-looppointerscounter

Comparing counters and pointers in string loops in C


I write these codes to read characters in a string

The first use Counter:

const char str[] = "Hello World!";

for (unsigned short i = 0; str[i]; i++) {
  char c = str[i];
}

The second use Pointer:

const char str[] = "Hello World!";

for (const char* i = str; *i; i++) {
  char c = *i;
}

So, who is better in performance? And why?


Solution

  • Based on my understanding of the answers and comments.

    the difference depends on the compiler used. If the compiler is good enough, there will usually compile to the same code.

    The primary difference would be in memory consumption, when using 16-bit (unsigned short) variable, or 64-bit (const char*) variable (pointer).