Pass by reference in C: how is the result variable initialized?

I'm new to C, and I need to make a mini-calculator program (this is homework, but I'm not looking for an answer, I just understand a little). Basically, one function should look like this:

int add(double d, double dd, double *result);

It will return 0 if there are no errors, and -1 if an error occurred (in the case of addition there would not be many errors, but division, for example, division by 0, would be an error).

The user must enter two numbers in the terminal, these numbers will then be used as parameter values ​​in the add method. What I do not understand is the result that initially occurs when the method is called? Is it just zero? And why do I want to return 0 or -1 and not the result? For instance:

double result;
returnValue = add(2.0, 5.0, &result); 

Obviously, I get 7 as a result, but how do I print this without returning a result? returnValue is 0, so I know there were no errors, so I need to print the result.

+5
source share
3 answers

C does not follow the link. You can pass in the pointer that you are doing here, but C has only a pass by value.

Now to your current questions:

What I don’t understand is the result when the method is called? Is it just null?

No, the value resultis undefined before the function is called add. You have no guarantees if you try to use a value resultbefore assigning it, either by assigning it the function in which it was declared, or by assigning it to the addcode, for example *result = d + dd.

null. Null - , .

0 -1, ?

result , - " " , . add , , , ( ).

, 7, , ?

< > Ed Heal printf. , Linux Mac OS X, man printf - , -.
+7

. .

returnValue = add(2.0, 5.0, &result);

, printf - .

+2

, , . , . , -, . , .

, , . , . , , :

double result = 7;

and it will always have a certain predetermined meaning. Again, there is no need to do this in your case, I just tell you if you always want a certain value.

0
source

All Articles