noname
noname

Reputation: 305

What does a return statement within a loop do?

In the code below, str_replace_all replaces all occurrences of oldc with newc. str_replace_first is only supposed to replace the first occurrence of oldc with newc.

So str_replace_all loops through and it replaces all occurrences of oldc with newc, easy enough to understand. In the second function str_replace_first the code is identical, except for return 1 after finding and replacing the char. I don't exactly understand what return 1 does in this case. From what I am understanding it "breaks" the loop? I was hoping somebody could give me an explanation on how it replaces only the first occurrence.

size_t str_replace_all(char s[], int oldc, int newc)
{
    size_t i;
    size_t count = 0;

    for (i=0; s[i]!='\0'; i++)
    {
        if (s[i] == (char)oldc)
        {
            s[i] = (char)newc;
            count++;
        }
    }
    return count; 
}


int str_replace_first(char s[], int oldc, int newc)
{

    size_t i;

    for (i=0; s[i]!='\0'; i++)
    {
        if (s[i] == (char)oldc)
        {
            s[i] = (char)newc; 
            return 1; /* What exactly does this do? */
        }
    }
        return 0; 
}

Upvotes: 1

Views: 92

Answers (2)

Raman
Raman

Reputation: 2785

Here in str_replace_first when

s[i] == (char)oldc

condition becomes true in the loop, then then that character(old character) is replaced by the new one. and then return 1 returns the control to the calling function with a value of 1.(i.e neither the loop nor the function continues further).

1 was returned to mark that only 1 character was replaced.

Upvotes: 0

FiringSquadWitness
FiringSquadWitness

Reputation: 686

return 1 escapes the function and returns a 1 to whatever has called it. return effectively escapes any function when it is called, this can be used in many applications to exit a function before it is 'complete'.

In this case:

int str_replace_first(char s[], int oldc, int newc)
{

    size_t i;

    for (i=0; s[i]!='\0'; i++)
    {
        if (s[i] == (char)oldc)
        {
            s[i] = (char)newc; 
            return 1; /* What exactly does this do? */
        }
    }
        return 0; 
}

The loop continues until it finds a character that matches oldc then replaces it with newc, then exits immediately before continuing on again. So as soon as it finds a match it will replace it then exit.

Upvotes: 1

Related Questions