Experimenting with function example

I'm just wondering if the int variable z is required or arbitrary. If it is preferable to my alternative I would appreciate knowing why. And perhaps when and where. Thanks for any feedback.

b52

// function example
#include <iostream>

int addition (int a, int b)
{
//int r;
//r=a+b;
int r(a+b); // int r(a+b) reads easier to me
return (r);
}

int main()
{
int a,b;
std::cout << "Enter a number: " << std::endl;
std::cin >> a;
std::cout << "Enter another number: " << std::endl;
std::cin >> b;

//int z;
//int z(addition(a,b));
//std::cout << "The result is " << z << std::endl;

std::cout << "The result is " << addition(a,b) << std::endl;

return 0;
}

closed account (S6k9GNh0)
Use [code] tags and I'll help out.
Welcome to the board. Yes, use code tags and indentation in the future - but FYI, not everyone here is going to be an asshole and refuse to answer someone's first ever (and short, at that) post, just because they didn't use code tags.

No, you don't need the variable z, unless you want to save the value for use later in the program. You can do either. It's not less efficient to use the variable, though, because the statement:

 
addition(a,b)


... implicitly creates a temporary value anyway.

Likewise, your function only needs to do this:

1
2
3
4
int addition(int a, int b)
{
    return a+b;
}




Last edited on
But Z will be created in the Data area of the memory and will stay there the whole runtime if it's defined in main, wouldn't it?
I'm not quite sure what you mean by the "Data" area of memory; perhaps you mean on the stack?

If you create and use a variable called "z" directly, instead of commenting that statement out, it will be valid as long as the current block is in scope. In this case, yes, the duration of the whole program.

Temporaries are only valid during the full expression in which they are created. The temporary variable created by the call to addition(a,b) during the statement:

 
std::cout << "The result is " << addition(a,b) << std::endl;


... goes out of scope immediately after the ';'.
Topic archived. No new replies allowed.