Thread: correct way of returning strings

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    47

    Question correct way of returning strings

    Hi Folks,

    i've a quiestion about returning strings correctly.
    is the following way a correcty one ?

    Code:
    		.
    		.
    		.
    		string token = nextToken();
    		if (token.empty())
    			done = true;
    		else
    		.
    		.
    		.
    		
    	
    string nextToken()
    {
    		string dummy;
    
    		reutrn (dummy);	// just return an empty string.
    }
    It works but is it safe to use it like this ???

    Regards,
    Robert

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Yes. This is the kind of thing strings are made for.

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    47
    ok. ...
    where is the varaible then created. ???
    Till now i thought that when a function is closed (return from) the stack is cleand up.
    So in this case the dummy would be deleted.

    Regards,
    Robert

  4. #4
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    Posts
    4,829
    The return value is copied into the value being assigned in the calling routine before the stack is unwound and the return completed. If no assignment is being made, the return value is discarded.

    In some cases, it can be more complicated than that where temporary copies are made first then copied into the calling routine. Particulaly the case when returning objects hence the need for copy constructors when returning objects from functions.
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

  5. #5
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    It is usually more efficient (unless you have a copy-on-write string implementation) to pass a string by reference instead:
    Code:
    string token;
    nextToken(token);
    
    void nextToken(string &out)
    {
      out = codeToGetToken;
    }

  6. #6
    Registered User
    Join Date
    Nov 2001
    Posts
    47

    Thumbs up

    Thanks guys !!


    -
    Robert

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Returning strings?
    By DBProgrammer in forum C++ Programming
    Replies: 4
    Last Post: 09-26-2007, 07:15 PM
  2. Strings Program
    By limergal in forum C++ Programming
    Replies: 4
    Last Post: 12-02-2006, 03:24 PM
  3. Please help with String class, returning strings
    By skanxalot in forum C++ Programming
    Replies: 4
    Last Post: 09-24-2003, 10:48 AM
  4. array of strings + more
    By null in forum C Programming
    Replies: 10
    Last Post: 10-01-2001, 03:39 PM
  5. returning strings
    By Unregistered in forum Windows Programming
    Replies: 1
    Last Post: 09-06-2001, 10:38 PM