I made this simple string length counter. I thought that was "elegant" to return "counter + 1" (to correct the position vs quantity adjustment usual fix) in a fancy way using "return counter++
". The fact is that it doesn't work. Compiles and runs perfectly, but with the counter++
the count is still one below the correct answer (i.e. same as a plain return counter
). And if i check for a second time the variable counter
still has the same value, so it was neither the case that "at the call (of the return), the expression was computed and if you check the variable value would be the desired".
int slength ( char source[] )
{
int counter = 0;
for (int i = 0; source[i] != '\0'; i++)
counter = i;
return counter + 1;
}
VS
int slength ( char source[] )
{
int counter = 0;
for (int i = 0; source[i] != '\0'; i++)
counter = i;
return counter++;
}
Why is my logic failing? Thank you.