0

I've found this and this and a few others but none really answer my question.

Ive done:

while ( *arr )

while ( *arr[i] != '\0' )

but i don't know if there's a better way

Miguel M
  • 302
  • 3
  • 16
  • 1
    `while ( *arr[i] != '\0' )` is only for strings – Abhilekh Gautam Jul 10 '21 at 14:51
  • 3
    The two examples you've shown aren't the same. Also, what's wrong with `for (int i = 0; i < len; i++){ /* Use arr[i] */ }` ? – Spikatrix Jul 10 '21 at 14:56
  • Typically only strings have a terminator at the end. Some array may have terminators, which may or may not be a zero. Otherwise you use the length (number of elements) in the array in a `for` loop. Which is most "optimal"? Test it out and profile and measure! – Some programmer dude Jul 10 '21 at 14:57
  • 2
    And why do you wonder? Is this really such a bottleneck in your program (profiled and measured) that you need to find another way to iterate over arrays? Otherwise, unless this is a top-three bottleneck in your code (which it very likely isn't, not the looping in itself I mean) bothering about micro-optimizations aren't really worth it. – Some programmer dude Jul 10 '21 at 14:59

1 Answers1

1

The first one is checking if the list of strings ends in a NULL pointer; the second is checking if the list of strings ends in an empty* string.

*I'm making an assumption here that i is zero; else this question makes no sense.

Using NULL as the terminator of a list of strings is always the faster API design both for the creator of the list and the consumer of the list.


Alternatively, you meant to ask if while (*arr) is faster or slower than while (*arr != '\0'). If your compiler isn't truly ancient these compile to the same thing so it makes no difference. Do whatever's easier to read.

Joshua
  • 40,822
  • 8
  • 72
  • 132