Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ C
In C++ and C programming languages is there any possibility for returning two values from a function?
Please help me, it's my interview question.
Posted 23-Aug-10 15:33pm
Edited 23-Aug-10 21:24pm
CPallini307.9K
v2
Comments
JackDingler at 26-Apr-12 12:29pm
   
This question is 2 years old.
 
Let it die...
armagedescu at 27-Apr-12 4:42am
   
Reason for my vote of 1
lame question on interview
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

If you don't know enough to pass your interview, getting answers to specific questions here will not get you a job. They don't all ask the same questions, and what they've done is expose your lack of basic C++ knowledge, something that no single question will help you with.
 
you can pass an object in as a pointer, and then changing it in your method will change it outside the method. You can also return your own struct that has the members you want to return, or if there's only two of them, the STL has a pair class you can use. If the objects are of the same type you can also return a container class, or just a pointer to a list of objects.
  Permalink  
Comments
Niklas Lindquist at 24-Aug-10 3:07am
   
Reason for my vote of 5
Complete answer.
CPallini at 24-Aug-10 8:55am
   
Nope, it isn't complete. The option of setting global variables (Oh My God!?!?!) is missing... :-D
Aescleal at 26-Apr-12 8:40am
   
Gag, bleugh.
 
Still dead right though, let's not advertise it though
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Literally speaking no.
But nothing prohibits a value to be "composite" and have more values in it.
Not to mention the fact that parameters can be reference, and the referred objects may be used as return values.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

It is always possible to return struct or pointer to struct from function. In C++ you can also return pair<first_type, second_type> Wink | ;)
  Permalink  
Comments
Christian Graus at 24-Aug-10 1:58am
   
Come on, already. No-one who is insisting on answering this question is adding anything to the answers already given !!!!
Albert Holguin at 26-Apr-12 14:32pm
   
lol, that annoys me as well when I answer a question... I did upvote your solution only.
Sauro Viti at 24-Aug-10 5:10am
   
Reason for my vote of 5
Good answer
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Technically a function can only return one value. So if you ever get asked if it's possible tell the interviewer that you can only ever return one value but that value could be a composite type.
 
If it's C++ then std::pair is quick solution. Unfortunately pair's members are imaginatively named first and second so you keep having to remember what they mean. For this reason it can be an idea to declare your own composite type to return with better names.
 
Cheers,
 
Ash
 
PS: As this question has returned to the top of the pile I thought I'd add this...
 
When you return a structure (the composite type I alluded to above) EVERYTHING in the structure is copied. And I mean EVERYTHING. And that happens in C and C++ (if you don't have a copy constructor). So you can write things like this (in C, don't try it in C++, it's not the done thing):
#include <stdio.h>

struct message
{
    char text[128];
};
 
/* Not a creative name, sorry! */
 
struct message return_a_message()
{
    struct message msg = { "Oo, what's this then?" };
    return msg;
}
 
int main()
{
    struct message msg = return_a_message();
    printf( "%s", msg.text );
 
    return 0;
}
My usual caveat applies here - I'm not in practise with C so someone that knows what they're talking about may be able to pick great holes in it. It might be poisoned by Microsoftisms as well.
 
Interestingly the VC++2010 compiler doesn't create a temporary to return the object, so it looks like C++ style NRVO is kicking in here. Cool!
 
PPS: I first saw this technique in "Expert C Programming" by Peter van der Linden sometime in the late 90s. If you're a C programmer go and buy a copy. Oh and ignore the C++ chapter it's well out of date and not particularly knowledgeably written (although amusing and thought provoking in places). Ah, screw it, read that chapter as well.
  Permalink  
v2
Comments
Aescleal at 27-Apr-12 9:11am
   
Anyone voting me down care to tell me why so I can learn something, modify my answer or just disagree with you and let the rating stand?
 
Cheers,
 
Ash
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

No. And if you don't know something as basic as this, you have no business attending interviews.
  Permalink  
Comments
Mohibur Rashid at 26-Apr-12 2:43am
   
not inspiring.
Keith Barrow at 26-Apr-12 8:05am
   
But accurate.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 11

Functions you write can return a maximumof a single value to their caller (you may write function that return no value when you use void ).
 
But if you wanna have a multiple values after calling the function you may use :
 
- structure or class as a return type ( a compmlex type holding more than one varialble).
 
- passing parameters by reference so the chnages will be kept even after function call.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 12

No, literally a function return only one value.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 8

Literally speaking of return where you use return keyword- NO.
But on common paradigms, yes - by pass by address.
 
In C#, its supported without the use of pointers. But still follows the concept of pass by address. Try to see, if not mistaken its with the use of out keyword
 
Sample code in c/c++:
 
int return2Values(float * fVal, int input)
{
// 2nd parameter is optional
// do something with fVal; basically, it changes the value it points
return /*some int value*/
}
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 7

Hi ,
 
you can make a function which will return one value and pass one parameter to it by reference and in function assign value to it.
 
Ex...
 
CString FunctionName(CString &strOut,int param1 , int param2 )
{
CString tempStr ;//Value to be assigned to ref parameter
CString strReturn;
 
..
.....
.......
//regular code
 
//at end
 
strout = tempStr;
return strReturn;
 
}
  Permalink  
Comments
Sauro Viti at 26-Aug-10 5:27am
   
This is something commonly used in COM programming, where methods return an HRESULT to report about failed/succeeded, and the "real" output of calls are obtained through parameters passed by address, like this:
 
HRESULT IUnknown::QueryInterface(REFIID riid, void **ppvObject);
 
However, I think that generally speaking, this is an unelegant solution and it's better to return a struct or class...
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 16

I can not understand why all the correct answers have been downvoted. The best answer to this stupid question would be to read a manual, because people with basic knowledge of C++ this language would never post such questions. And even worse knowledge have those who downvoted all the correct answers.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 17

I can not understand why all the correct answers have been downvoted. The best answer to this question would be to read a manual, because people with basic knowledge of C++ this language would never post such questions. And even worse knowledge have those who downvoted all the correct answers.
  Permalink  
Comments
Jochen Arndt at 5-Jul-12 4:56am
   
Because the question is from the year 2010 and the interview should have been finished meanwhile. So please stop bringing it on top again.
armagedescu at 5-Jul-12 8:09am
   
It was actually in the top when people responded. It is not a problem to ignore a question for people who is not interested in it. I am not addicted to newest questions. I've only seen it and posted the answer. It is a valid rule for any forum, no one can prohibit others to answer questions.
Jochen Arndt at 5-Jul-12 8:31am
   
It was on the top, because others (and you) missed that it is outdated. Answers are mainly directed to the questioner. With this one, there is no need for additional answers (you already noted that no one with basic C++ knowledge will benefit).
 
I did not prohibit you to answer. I kindly asked to stop it here. Because you did not answer the question but where moaning about downvoting. And that's the best method to get more downvotes here at CP.
 
In this thread, I downvoted only your double posts 16 and 17 and no other one.
armagedescu at 5-Jul-12 8:11am
   
Hope appearing of old questions in top is not a good reason for downvoting wars.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 6

A recursive function code can also
return a value for several times
by one call from outside...
 
...since there is no term "call" (but "function")
in your interview question... Big Grin | :-D
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 10

int main()
{
    //int a1[]={2,3,4};
    int *a=<pre lang="cs">oneOrMoreReturn();
    std::cout&lt;&lt;*(a+1)&lt;&lt;std::endl;
    std::cout&lt;&lt;*(a+0)&lt;&lt;std::endl;
    std::cout&lt;&lt;*(a+2)&lt;&lt;std::endl;
    int b;
    cin&gt;&gt;b;
}
int * oneOrMoreReturn()
{
 
    int a1[]={2,3,4};
    return a1;
 
 }</pre>
  Permalink  
Comments
Stefan_Lang at 27-Apr-12 12:00pm
   
voted down for (in order of severity):
- thread necromancy
- proposing an unsafe method (returning a temporary, although it actually might work in this case)
- lack of explanation
- bad formating
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 14

like this:
void func(type1* ret1, type2* ret2)
{
...
*ret1 = x;
*ret2 = y;
...
}
 
use function like this:
type1 var1;
type2 var2;
 
func(&var1, &var2)
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 13

Use pointers as input parameters
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 9

Some functions
can also return two logical values by one physical value Big Grin | :-D :
_AFXWIN_INLINE HWND CWnd::GetSafeHwnd() const
{
  return this == NULL ? NULL : m_hWnd;
}
 
void TestWnd(CWnd* pcWnd)
{
  // Please note: no additional check of the pointer is needed
  if (pcWnd->GetSafeHwnd()) {
    // the window was created(2) at an allocated(1) pointer :)
    pcWnd->SetWindowText(_T("Checked"));
  }
}
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 15

How about this
int AddOne(int toThis)
{
  return toThis + 1;
}
 
...
int Value = 1;
Value = AddOne(Value); //Here it returns 2
Value = AddOne(Value); //Here it returns 3
The same function returned 2 different values. Hey, the question didn't say "at once", now did it? Smile | :)
 
But seriously, doesn't this kind of depends on the definition of 'value', if you e.g. have a function that returns a 4 byte integer, you could also say it returns 2x2 bytes values (e.g. 2 shorts) or 4x1 byte values (e.g. chars) packed into one integer. How about it?
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 CHill60 240
1 Sarvesh Kumar Gupta 238
2 Sergey Alexandrovich Kryukov 193
3 DamithSL 153
4 OriginalGriff 138


Advertise | Privacy | Mobile
Web03 | 2.8.140709.1 | Last Updated 5 Jul 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid