In and out params

For functions, it’s handy to be able to identify what’s an “in” parameter, versus what’s an “out” parameter. I just got done reading an article about the Doom3 engine source code and there was something that I liked.

  1. From this signature you can identify what is an “in” and what is an “out”.
  2. The return type is obviously an “out”.
  3. The “const int val” identifies this as an “in”, even though it’s just an int.
  4. const Data& d1 is an “in”.
  5. For d2, it’s an out, and this is obvious because it takes a double pointer.
  6. For d3, this is also obviously an out. You want the function to fill something out.
  7. All out parameters use pointers, all in parameters use const or const refs.
  8. Never use a parameter as both an “in” and an “out”.

For #6, when you call this function look at what it looks like.

You can tell by looking at how it’s called what is an input and what is an output. If it has an &, you know it’s an out. Except for the return value obviously. You also have a guarantee that counter or data won’t be modified, and it won’t be modified inside the function. The function could copy the value and change it there as a separate variable on the stack, but that requires extra work. This is all about simple guarantees. I really like this approach, and I think I will adopt it for my standards.

Comments are closed.