Home > Back-end >  Difference between return type and break type
Difference between return type and break type

Time:06-05

I am a beginner in C and I created a program which does the following :

  • read input from keyboard .
  • store the words to a dynamically allocated array until read the word bag
  • print the first word of the array

When I replace the break statement with return I notice that does not print the first word of the array in contrast with break statement (Why is this happened?)

In case of return :

If I have the following input

  1. vld
  2. pkd
  3. lok
  4. bag

At the moment which input is bag everything is stored in array (I mean the words vld,pkd ,lok) is lost?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>



void word() {
    int  num = 0 , i = 0;
    char s[10];
    char **str;

    for(;;)
    {   gets(s);
        if (strcmp(s ,"bag")== 0 )
        {
            break;  // return;
        }
    }
    num  ;
    str = (char **)malloc(sizeof(char*)*num);
    str[num - 1] = (char*)malloc(sizeof(char)*strlen(s) 1);
    str[num - 1] = strdup(s);
    printf("the word is : %s",str[0]);

}



int main()
{
    word();
    return 0;
}

CodePudding user response:

return means you're exiting the function. However break just exits the loop. I'm concerned about other issues with your code, namely using gets(). See why not use gets.

In case of using return, the control flow goes back to your main function, which means s is de-allocated as it goes out of scope, and dynamically allocated objects become dangling objects. see memory leak

A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code

In your case however, using return, the control flow would never reach the malloc() call so you wouldn't necessarily have memory leaks.

Edit : In fact, all automatic variables are de-allocated and freed when they go out of scope. see Scope

the scope of a name binding—an association of a name to an entity, such as a variable, is the part of a program where the name binding is valid, that is where the name can be used to refer to the entity. In other parts of the program the name may refer to a different entity, or to nothing at all

CodePudding user response:

break brings the program control out of the loop, so, your lines in the function after the loop will be executed normally. return ends the function, so it will break from your loop AND your function. So, the behavior you have experienced is expected.

  • Related