Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
2.00/5 (3 votes)
See more:
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
Updated 23-Aug-10 21:24pm
v2
Comments
JackDingler 26-Apr-12 12:29pm    
This question is 2 years old.

Let it die...
armagedescu 27-Apr-12 4:42am    
Reason for my vote of 1
lame question on interview

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.
 
Share this answer
 
Comments
Niklas L 24-Aug-10 3:07am    
Reason for my vote of 5
Complete answer.
CPallini 24-Aug-10 8:55am    
Nope, it isn't complete. The option of setting global variables (Oh My God!?!?!) is missing... :-D
Aescleal 26-Apr-12 8:40am    
Gag, bleugh.

Still dead right though, let's not advertise it though
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.
 
Share this answer
 
It is always possible to return struct or pointer to struct from function. In C++ you can also return pair<first_type, second_type> ;)
 
Share this answer
 
Comments
Christian Graus 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 26-Apr-12 14:32pm    
lol, that annoys me as well when I answer a question... I did upvote your solution only.
Sauro Viti 24-Aug-10 5:10am    
Reason for my vote of 5
Good answer
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):
C++
#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.
 
Share this answer
 
v2
Comments
Aescleal 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
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? :)

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?
 
Share this answer
 
No. And if you don't know something as basic as this, you have no business attending interviews.
 
Share this answer
 
Comments
Mohibur Rashid 26-Apr-12 2:43am    
not inspiring.
Keith Barrow 26-Apr-12 8:05am    
But accurate.
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.
 
Share this answer
 
No, literally a function return only one value.
 
Share this answer
 
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)<br />
{<br />
    // 2nd parameter is optional<br />
    // do something with fVal; basically, it changes the value it points<br />
    return /*some int value*/<br />
}
 
Share this answer
 
Some functions
can also return two logical values by one physical value :-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"));
  }
}
 
Share this answer
 
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;

}
 
Share this answer
 
Comments
Sauro Viti 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...
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.
 
Share this answer
 
Comments
Jochen Arndt 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 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 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 22-Aug-21 5:15am    
So, should I not respond just because of that irritates someone who is hunting updates? That looks very personal.
armagedescu 22-Aug-21 5:09am    
Really? Looks like very personal attitude.
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.
 
Share this answer
 
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... :-D
 
Share this answer
 
C#
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>
 
Share this answer
 
Comments
Stefan_Lang 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
like this:
void func(type1* ret1, type2* ret2)
{
...
*ret1 = x;
*ret2 = y;
...
}

use function like this:
type1 var1;
type2 var2;

func(&var1, &var2)
 
Share this answer
 
Use pointers as input parameters
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900