0

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.

nostromo
  • 61
  • 1
  • 1
  • 11
  • 1
    Because `counter++` increments `counter` **as a side effect** and **evaluates to** the **old** value of `counter`. – Karl Knechtel Apr 03 '23 at 08:38
  • 1
    Because `counter++` increments the value of variable counter after processing the current statement. To achieve a similar behaviour to the first function, you would need to `return ++counter`. – jvieira88 Apr 03 '23 at 08:53
  • Uau! @jvieira88 great hint, worked perfectly. I think (prove me wrong anyone) i didn't find this, your alternative, in https://stackoverflow.com/questions/16505359/what-happens-to-the-increment-of-b-in-return-b-if-used-in-a-function (although it was probably deductible from the post, thanks also to the admin). Thank you. – nostromo Apr 03 '23 at 09:00

0 Answers0