tags:

views:

217

answers:

5

I am learning C. And, I see this function find length of a string.

size_t strlen(const char *str) 
{ 
 size_t len = 0U; 
 while(*(str++)) ++len; return len; 
}

Now, when does the loop exit? I am confused, since str++, always increases the pointer.

+11  A: 
while(*(str++)) ++len;

is same as:

while(*str) {
 ++len;
 ++str;
}

is same as:

while(*str != '\0') {
 ++len;
 ++str;
}

So now you see when str points to the null char at the end of the string, the test condition fails and you stop looping.

codaddict
+1 IMO the best way to explain this - through rewriting "one step at a time".
sharptooth
"is same as:" except for the final value of `str`, but that's unused in this case.
Steve Jessop
A: 

Once *(str++) returns 0, the loop exits. This will happen when str points to the last character of the string (because strings in C are 0 terminated).

sepp2k
+9  A: 
  1. C strings are terminated by the NUL character which has the value of 0
  2. 0 is false in C and anything else is true.

So we keep incrementing the pointer into the string and the length until we find a NUL and then return.

doron
I knew the the first point. The second made it clear!! Thanks
jess
@doron: I am ok with your answer, but for the mentioning of ASCII. Would be better to leave that out. `nul` is guaranteed to be `0` with any encoding.
Jens Gustedt
@Jens amended as per your recommendation.
doron
@doron: great, thanks
Jens Gustedt
+2  A: 

You need to understand two notions to grab the idea of the function :

1°) A C string is an array of characters.

2°) In C, an array variable is actually a pointer to the first case of the table.

So what strlen does ? It uses pointer arithmetics to parse the table (++ on a pointer means : next case), till it gets to the end signal ("\0").

Raveline
table of characters? Do you mean array of characters?
Manoj R
Yep. I always make this mistake in english (in french, we say "tableau" for "array", so I tend to go with "table").
Raveline
A: 

Correct, str++ increases the counter and returns the previous value. The asterisk (*) dereferences the pointer, i.e. it gives you the character value.

C strings end with a zero byte. The while loop exits when the conditional is no longer true, which means when it is zero.

So the while loop runs until it encounters a zero byte in the string.

gclj5