I am new to C, and I have to make a mini calculator program (this is homework, but I’m not looking for the answer, just a little more understanding). Basically, one function must look like this:
int add(double d, double dd, double *result);
It will return a 0 if there are no errors, and -1 if an error occurred (in the case of addition, there wouldn’t be many errors – but division for example, divide by 0 would be an error).
A user has to input two numbers into the terminal, those numbers then get used as the parameter values in the add method. What I don’t understand is what is result initially when the method is called? Is it just null? And why would I want to return 0 or -1 and not result instead? For example:
double result;
returnValue = add(2.0, 5.0, &result);
Obviously I’ll get 7 as the result, but how will I print that out without returning the result? returnValue is 0, so I know there were no errors, so now I need to print result.
C doesn’t have pass by reference. You can pass in a pointer, which is what you’re doing here, but C only has pass by value.
Now to your actual questions:
No, the value of
resultis undefined before theaddfunction is called. You have no guarantees whatsoever if you try to use the value ofresultbefore assigning to it, either by assigning to it in the function where it’s declared or by assigning to it inaddwith code like*result = d + dd.For that matter, a double can never be
null. Null is a possible pointer value, not a possible floating-point number.If you were to return
resultdirectly, you’d have to have some kind of distinguished “calculation failed” return value, which is kind of messy and leaves the caller to check the result before using it. This way forces the caller ofaddto notice that there is status code as the return value, and if the caller wants to ignore it then they can (although you shouldn’t ignore status codes).Ed Heal is right to suggest
printf. If you’re using Linux or Mac OS X, though, I’d also recommend runningman printffrom the terminal – it’s often more convenient than opening a web browser.