Functions Help C++

Started by
4 comments, last by Simian Man 17 years ago
#include <stdafx.h> #include <IOSTREAM.h> using namespace std; int main() { int a = 10; int b = 20; int answer = add(a, b); cout << "This is the value returned by the function add: " << answer << endl; return 0; } int add(int i, int j) { return i + j; // return statement } Is it legal to declare i and j in a function and have those values turn into a and b by returning a value from the function add()? How does this happen? Need a little clarification please
Visit http://www.myspace.com/miguelchang
Advertisement
Quote:Original post by Miguel Chang
Is it legal to declare i and j in a function and have those values turn into a and b by returning a value from the function add()?

How does this happen? Need a little clarification please


I'm not quite sure what you mean. As you're code is now, it probably won't compile because you need to either define or declare your add function before main(). Also, the correct c++ header is <iostream>, not <IOSTREAM.h>.

If your code were to compile, it would do something like the following:
Create ints a and b, and assign to them the values of 10 and 20, respectively.
Then it would call add, which would have two variables of its own, i and j. These variables would be copies of a and b, and as such, would have the values of a and b.
The add function would add i and j to get 30, and return that value. This value would then be stored in the int answer.
And for the sake of good habits

int add(int i, int j)

should be either

int add(const int i, const int j)

or

int add(const int& i, const int& j)

Omae Wa Mou Shindeiru

Moving you to For Beginners.

- Jason Astle-Adams

Quote:Original post by LorenzoGatti
And for the sake of good habits

int add(int i, int j)

should be either

int add(const int i, const int j)

or

int add(const int& i, const int& j)
Um, what? No it shouldn't. Types less than or equal to the native type size (which is int) should be passed by value unless they're to be modified by the function. Passing by constant value is redundant.
Quote:Original post by Evil Steve
Passing by constant value is redundant.


Well it's not quite redundant because it implies that not only will the passed parameters not be changed, but also the variables won't be changed inside the function (they're const local variables). But it is silly [smile].

This topic is closed to new replies.

Advertisement