2

Possible Duplicate:
returning multiple values from a function

I've stuck in dot with returning 2 values to stack. My task is to write a program which calculates complex numbers. Everything is fine but one thing. In function which divides numbers I want to make 2 cases:

  1. if number by which I divide doesn't equal 0, just divide and return result as one value.
  2. if number by wchich I divide EQUALS 0, I want to return 2 values.

For complex numbers I use structures (double real and double imaginary numbers). The function I use is in type of complex number structure. By function return I can only return 1 value. How can I return the second one to have on stack the same amount of numbers as before dividing? I know that I should use pointers but I still can't figure out how to use them here.

Community
  • 1
  • 1
Shazin
  • 71
  • 7

1 Answers1

6

Since you already have a struct for a complex number (which I'll call complex), you could just return an instance of:

struct one_or_two_complexes { 
     int howmany; 
     struct complex first; 
     struct complex second; 
};

Whether that's a good idea probably depends how the caller is expected to use it

In the case where the caller knows for sure that the divisor isn't zero, they can just write complex result = your_function(a,b).first;, which is nice.

In the case where the caller isn't sure, and wants to do something different according to whether it is zero or not then they can either store the result of the function call in their own instance of one_or_two_complexes and then check howmany, or they can check for themselves whether the divisor they pass in is zero or not, and call your function differently in the different cases.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
  • +1 I didn't knew that `result = your_function(a,b).first;` is valid syntax in C language. I had never seen it before. I had in mind the . operator only work in variables. – Jack Jan 03 '13 at 19:37