in C Plus Plus by
How would you handle a situation where you need a function to return multiple values?

1 Answer

0 votes
by

In a situation where multiple values need to be returned from a function, there are several strategies that can be employed. One common method is to return the values as a tuple or list. This allows for an arbitrary number of values to be returned and accessed by indexing into the returned object.

For example, in Python:

def multi_return():
return 1, 2, 3
a, b, c = multi_return()

Here, 

multi_return

 returns a tuple 

(1, 2, 3)

, which is then unpacked into variables 

a

b

, and 

c

.

Another approach is to use a dictionary or similar key-value data structure. This provides more flexibility than a list or tuple because it allows the caller to access the returned values by name rather than by position.

Example:

def multi_return():
return {'first': 1, 'second': 2, 'third': 3}
result = multi_return()
print(result['first'])
...