Reputation: 249
The variables are not accepting the values I'm entering in my C++ program. I must avoid global variables and use only local variables. And the function returns nothing, so I have used "void" instead of "int" type. Same thing happening when I use strings or any type of custom function. Here is the example to explain my problem:
#include <iostream>
void sum (int a, int b, int c);
int main (void)
{
int a = 0, b = 0, c = 0;
sum (a, b, c);
std::cout << a << b << c;
return 0;
}
void sum (int a, int b, int c) // It doesn't have to be the same variable name :)
{
std::cout << "Enter value of a:\n";
std::cin >> a;
std::cout << "Enter value of b:\n";
std::cin >> b;
std::cout << "Enter value of c:\n";
std::cin >> c;
a = b+c;
}
Upvotes: 4
Views: 1826
Reputation: 329
Arguments can be passed by value or by reference to a function.
When you pass an argument by a value (which is what you are doing), a separate copy is created of the variable and is stored in a different memory location.
When you pass by reference (using a pointer), same memory location is referenced. Basically in your code you are creating a separate copy of the variable referenced by the same name and modifying that copy and expecting the changes in the original. The solution is to use pointers.
Upvotes: 0
Reputation: 707
You can use pass by reference (or by pointer, for the educational purpose):
void sum (int& a, int& b, int& c);
void sum (int* a, int* b, int* c);
int main (void)
{
int a = 0, b = 0, c = 0;
sum (a, b, c);
std::cout << a << b << c;
a = 0, b = 0, c = 0;
sum (&a, &b, &c);
std::cout << a << b << c;
return 0;
}
void sum (int& a, int& b, int& c)
{
std::cout << "Enter value of a:\n";
std::cin >> a;
std::cout << "Enter value of b:\n";
std::cin >> b;
std::cout << "Enter value of c:\n";
std::cin >> c;
a = b+c;
}
void sum (int* a, int* b, int* c)
{
std::cout << "Enter value of a:\n";
std::cin >> *a;
std::cout << "Enter value of b:\n";
std::cin >> *b;
std::cout << "Enter value of c:\n";
std::cin >> *c;
*a = *b + *c;
}
Upvotes: 2