How to set a variable value in C ++ when it is not in the global scope and used in a user-defined function?

Variables do not accept the values ​​that I entered in my C ++ program. I should avoid global variables and use only local variables. And the function does not return anything, so I used "void" instead of the type "int". The same thing happens when I use strings or any type of user-defined function. Here is an 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;
}
+4
source share
3 answers

You can use the pass by reference (or a pointer for educational purposes):

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;
}
+1
source

Follow the link :

void sum (int &a, int &b, int &c)
+7

Arguments can be passed by value or by reference to a function.
When you pass an argument to a value (which you do), a separate copy of the variable is created and stored in another memory location.
When you follow a link (using a pointer), it refers to the same memory location. Basically, in the code, you create a separate copy of the variable referenced by one name, and change that copy and expect changes in the original. The solution is to use pointers.

0
source

All Articles