How many arguments can a return statement have
Is this possible
return(n-1,m+1)
in this case what will it return and why
Short answer: a single expression is returned. is correct that you don't get two separate return values, and / were pointing at the right pitfalls around arrays and lifetime — but there’s a wrinkle worth explaining.
If you write a return that contains two comma-separated subexpressions (for example return (e1, e2);) you are using the comma operator: e1 is evaluated (side effects happen) and discarded, and the value of e2 is the actual return value. That often surprises people who expect both sides to be "returned." See the and the return statement.
If the goal is to produce multiple outputs, return an aggregate instead (struct, std::pair, std::tuple) or use out-parameters. Example pattern:
std::pair<int,int> adjust(int n, int m) {
return { n-1, m+1 };
}
auto [newN, newM] = adjust(n, m); // C++17 structured bindings Returning objects by value is fine in modern C++: copy elision and move semantics make it efficient (copy elision). Do not return references or pointers to local (automatic) variables — that causes undefined behavior (see object lifetime). Use std::unique_ptr or containers if you must transfer ownership.
Jump to Post— Salem 6,009Just one, read your book.
Just one, read your book.
But in case you don't have a book...
return can only be passed one value. However it could be an array if they are of the same type.
>>But in case you don't have a book...
Buy, Beg, Borrow or Steal one.
But in case you don't have a book...
return can only be passed one value. However it could be an array if they are of the same type.
That depends on what sort of "array". A locally declared array, such as int ret_arr[10]; cannot be the return value, nor can a C-style string. On the other hand, C++ strings or STL containers (vectors, for example) can be returned.
Val
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.