info on "return" order in functions

This is a discussion on info on "return" order in functions within the C Programming forums, part of the General Programming Boards category; i discovered these facts about using return in a function while experimenting on my own. take this following function for ...

  1. #1
    Counter-Strike Master
    Join Date
    Dec 2002
    Posts
    38

    info on "return" order in functions

    i discovered these facts about using return in a function while experimenting on my own. take this following function for example:
    Code:
    char getchen(void);
    
    char getchen(void)
    {
    	char ch;
    
    	ch=getche();
    	return ch;
    	printf("\n");
    }
    here i needed the character to be displayed before the carriage return so i thought inserting the return statement at this point would make it work properly. it ended up ignoring everything after the return statement. here is the correct code and explination:
    Code:
    char getchen(void);
    
    char getchen(void)
    {
    	char ch;
    
    	ch=getche();
    	printf("\n");
    	return ch;
    }
    i discovered that the order of return doesnt matter. it always has to be last and all it gives is a reference to the variable that has to be returned. it doesnt necesarily have to be placed where you want the variable to return as i learned from trial and error

    hope this was useful to somebody, thx 4 reading. post some replies for me
    You say "Impressive!", but I already know it
    I'm a hardcore player and I'm not afraid to show it

  2. #2
    Registered User
    Join Date
    Jul 2003
    Posts
    450
    it always has to be last and all it gives is a reference to the variable that has to be returned.
    It doesn't necessarily have to be last, as in a conditional return
    Code:
    bool function()
    {
          // do some stuff
            .
            .
    
          if (condition)
             return true;
          
          //do more stuff
         return false;
    }
    just a crude example of how you may want to return from a function in certain situations

  3. #3
    Counter-Strike Master
    Join Date
    Dec 2002
    Posts
    38
    well, ignoring that minor technical detail. that pretty much covers the return statement and how it messed me up
    You say "Impressive!", but I already know it
    I'm a hardcore player and I'm not afraid to show it

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by Bigbio2002
    well, ignoring that minor technical detail. that pretty much covers the return statement and how it messed me up
    Whenever a return statement is encountered, the function returns. The newline in your first example is not printed, because the function immediately returns.

    In your second example, the newline is printed first, and then the function returns.
    here i needed the character to be displayed before the carriage return so i thought inserting the return statement at this point would make it work properly. it ended up ignoring everything after the return statement.
    This is correct. This is working exactly as it should.

    i discovered that the order of return doesnt matter. it always has to be last and all it gives is a reference to the variable that has to be returned. it doesnt necesarily have to be placed where you want the variable to return as i learned from trial and error
    No, this is wrong. Whenever a return is encountered, the function immediately returns.

    Whether or not your other code executes right has nothing to do with the way return works. It is your just misunderstanding how the logic of the code works.

    In short:

    1) If a function doesn't return anything, meaning it is a void function, then return is not needed at all, unless you wish to "break out of" the function early. Example:
    Code:
    void function( int x )
    {
        int y = 0;
    
        for( y = 0; y < x; y++ )
        {
            if( y == 5 )
                return;
        }
    
        printf("x was less than 5\n");
    }
    Crude example, but it illustrates the point. Here, we want the function to end if y ever reaches five. If it doesn't, then it will continue on and issue the printf statement. Notice that we do not need a return at the end of this function, because it is a void function.

    2) If a function is non-void, meaning it returns a value, then you must return a value of the appropriate type whenever you return from the function. Example:
    Code:
    int function( int x )
    {
        int y = 0;
    
        for( y = 0; y < x; y++ )
        {
            if( y == 5 )
                return x;
        }
    
        printf("x was less than 5\n");
        return y;
    }
    This function requires two return statements. The function breaks early in the loop, if the right condition is met, and so it has to return an integer there, since that's the return type this function requires. It also needs one at the end, because the end of the code block is reached and the function requires an integer be returned.

    In this example, it doesn't matter what we return, as long as it is an integer, since that's what the function declaration requires of us.

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,590
    AFAIK a return in C is a LEAVE and RET in assembler. Truth be known all functions 'return' whether or not you specifically place a return in them or not. It's just that C uses this mechanism to easily identify functions that return values. All integral return values are in (E)AX and all floating point return values are in ST0.

    So even void functions return although in C this is not a good way to think of void functions.

    All that return means is that whatever is after the return statement will be stored in EAX or ST0. So then the compiler knows what value to assign your variable when you do something like :

    int x=MyFunc(y);

    roughly translates to:

    push [y]
    call MyFunc
    ;return value is in (e)ax
    mov [x],eax

    Note that eax could be a pointer to a structure, class, or other user defined object.

  6. #6
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,528
    Quzah wrote:
    1) If a function doesn't return anything, meaning it is a void function, then return is not needed at all, unless you wish to "break out of" the function early. Example:

    Code:
    void function( int x )
    {
        int y = 0;
    
        for( y = 0; y < x; y++ )
        {
            if( y == 5 )
                return;
        }
    
        printf("x was less than 5\n");
    }
    Crude example, but it illustrates the point. Here, we want the function to end if y ever reaches five. If it doesn't, then it will continue on and issue the printf statement. Notice that we do not need a return at the end of this function, because it is a void function.
    Ok, so you said this is a crude example - but it is perfectly acceptable to use a return to break out of a function and return to the calling function? I am making an accounting program, and I use a do while loop for the main menu - it is a separate function - then if I choose one of the items (except quit) that calls another function, and another menu displays. So from the second menu, if I want to return to the main menu, I choose something like '3) Return to main menu' - and then in my code use a return statement like this:

    Code:
      case '3': 
    	       printf( "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" );
    	       printf( "\nReturning to the main menu...\n\n" );
    	       getchar( );
    	       return;
    	       break;
    Where choice three corresponds to 'Return to main menu' on the user's display. Good? Bad?

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,461
    I think we're verging on the "goto" topic in the C++ forum:
    goto question

    I'd say it's ok, but comment it.
    Also, the break is redundant for that case.

  8. #8
    Counter-Strike Master
    Join Date
    Dec 2002
    Posts
    38
    wow, ok that was all cofusing.
    Whether or not your other code executes right has nothing to do with the way return works. It is your just misunderstanding how the logic of the code works.
    i guess as long as it works i shouldnt bother with the low level technical stuff. the part i dont understand is that even though it returns the value last, how come it displays the character from getche() before the newline? i ought to stop thinking...

    also, i feel kinda stupid typing in all lowercase and looking at all of you with neatly formatted replies
    You say "Impressive!", but I already know it
    I'm a hardcore player and I'm not afraid to show it

  9. #9
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,590
    I was simply explaining to you that all functions return no matter what. Now for the sake of pure C you only use a return upon returning from a function that returns a value. All functions do return - but void functions have an intrinsic return that the compiler puts in for you - functions that return a value have an intrinsic return - but the compiler does not know what to return so you must tell it.

    A good programming habit to get into is one entry point and one exit point per function and - one function does one thing. Using a return to leave a function mid-way is not a good practice. The only reason I can see to use a return midway through a function is in a recursive function.

    Exiting out of a function mid-way makes your code very hard to follow and also violates several rules - although it can be done.


    The proper way to use a return statement is this:

    Code:
    int Add(int a,int b)
    {
      return (a+b);
    }

    You can also return pointers to objects and classes. You can also return arrays but I don't recommend doing it. If you need to fill an array do it like this or simply return a pointer to the array. You can return an array via the stack but again I don't recommend doing it although it is possible.

    Code:
    //Adds array1 and array2 and puts result in arraytoset
    void SetArray(int array1[2][2], int array2[2][2],int arraytoset[2][2])
    {
      for (int ii=0;ii<2;i++)
      {
         for (int j=0;j<2;j++)
         {
            arraytoset[ii][j]+=array1[ii][j]+array2[ii][j];
         }
       }
    }
    Have to use ii or board will interpret it as italics not array.

    When a C function returns, that function is responsible for cleaning up the stack. I cannot explain to you the entire stack process as it would only serve to confuse you at this juncture.

    NOTE: Is there a way to turn off the bold italic and other things inside of a code section. Look at the above example. The board sees my 'i' as an italics command, not as part of a C array. So it puts everything in italics after that. Then when I want to use italics again....it fails because it's looking for a '/i'.
    ???
    Last edited by VirtualAce; 11-19-2003 at 03:51 PM.

  10. #10
    Registered User
    Join Date
    May 2003
    Posts
    161
    > Now what you don't want to do to often is this:

    Bubba, I don't see a problem with either of those functions (except that you're using the new operator on the C board). Returning stack allocated data is fine-- a copy of the data is made. The problem is when you return a pointer to stack allocated data like so:
    Code:
    int *somefunc()
    {
      int i = 10;
      return &i;
    }
    You'd be returning a pointer to data that may be cleaned up and/or reused.

  11. #11
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,590
    You are correct, sir. Post edited to reflect this.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-03-2008, 11:31 AM
  2. Embedded SQL Order By
    By cjohnman in forum C Programming
    Replies: 12
    Last Post: 04-15-2008, 03:45 PM
  3. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 05:58 PM
  4. Replies: 3
    Last Post: 12-06-2001, 04:30 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21