简体   繁体   中英

In C++ Output Parameter vs Return Value

What is/are the difference(s) between output parameters and return values? I've looked everywhere and I can't seem to find a simple definition for either.

  • The return value is something well defined in C++; for instance, x in return x; is the return value, whereas int in the function declaration int myfunc() is the return type.
  • The concpet of output paramters is not defined in C++. However someone would interpret it as either of the following:
    • function parameters passed by non- const reference, as long as you actually modify it in the function , otherwise why would you call it output ? An example is x in the following function declaration: void myfunc(int& x) ;
    • function parameters passed by (not necessarily const ) pointer to non- const , like x in both the following function declarations: void fun1(int * x) and void fun2(int * const x) ;
      • concerning this latter case, it allows "encoding" a missing parameter in as a nullptr default value, as in void fun3(int * x = nullptr) .

A first difference is aesthetic: which one you like the most?

Another one is that the former concept and syntax help you convey the message that the function is giving back a value, something which is clear at the call site too (whereas at the call site you might not know if a parameter corresponding to an argument is passed by reference or not).

There are several differences between this two ways a function can have "consequences" at the caller site. For instance, you can only have one return value, whereas you can have as many paramters as you like.

Performancewise, complier optimizations can minimize the difference in performance, and maybe you should not worry (yet) about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM