Miguel M
Miguel M

Reputation: 370

What is the OPTIMAL way to iterate through an array or string in C?

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

Upvotes: 0

Views: 273

Answers (1)

Joshua
Joshua

Reputation: 43280

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.

Upvotes: 1

Related Questions