CodingHero
CodingHero

Reputation: 3025

In c++ do you have 'out parameters' like in c#?

In c++ do you have 'out parameters' like in c#?

In c# the method signature would be:

bool TryGetValue(int key, out OrderType order)

The idea is the variable may not be assigned before passed but MUST be assigned before exiting the method.

MSDN out params link: http://msdn.microsoft.com/en-us/library/aa645764(v=vs.71).aspx

Upvotes: 4

Views: 3456

Answers (5)

JaredPar
JaredPar

Reputation: 754853

There is nothing as strict as C# out parameters in C++. You can use pointers and references to pass values back but there is no guarantee by the compiler that they are assigned to within the function. They are much closer to C# ref than out

// Compiles just fine in C++
bool TryGetValue(int key, OrderType& order) {
  return false;
}

Upvotes: 6

Ferruccio
Ferruccio

Reputation: 100668

You can use references or pointers to simulate out parameters, but a better way is to use tuples (std::tuple in C++11 or boost::tuple in C++98/03) to return multiple values from a function. You cannot return without a complete tuple.

#include <tuple>

std::tuple<bool, OrderType> TryGetValue(int key) {
    OrderType ot;
    ...
    return std::tuple<bool, OrderType>(true, ot);
}

...

bool b;
OrderType o;
std::tie(b, o) = TryGetValue(k);

Upvotes: 1

Huang F. Lei
Huang F. Lei

Reputation: 1865

If you really like a 'out' keyword, you can define a maro:

#define out

as a mark, although it has not effect for compiler.

Just like some one would define 'public', 'private' keyword for C.

Upvotes: 3

Some programmer dude
Some programmer dude

Reputation: 409196

That would be one use of references:

bool TryGetValue(int key, OrderType &order)

Then you can simply assing to order and the calling function would get the data.

Upvotes: 0

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

No, there are no out parameters in C++ that force you to assign to it before exiting the function. Pointers and references are more like ref parameters in C#.

Upvotes: 5

Related Questions