简体   繁体   中英

How to set value of a variable in C++ when it's not in global scope and used in custom function?

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;
}

通过引用传递

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

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM