How do I return multiple values from a function in C?

前端 未结 8 1118
深忆病人
深忆病人 2020-11-22 15:14

If I have a function that produces a result int and a result string, how do I return them both from a function?

As far as I can tell I can

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 15:43

    Two different approaches:

    1. Pass in your return values by pointer, and modify them inside the function. You declare your function as void, but it's returning via the values passed in as pointers.
    2. Define a struct that aggregates your return values.

    I think that #1 is a little more obvious about what's going on, although it can get tedious if you have too many return values. In that case, option #2 works fairly well, although there's some mental overhead involved in making specialized structs for this purpose.

提交回复
热议问题