Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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;
}
like image 481
Amession Avatar asked Feb 13 '23 05:02

Amession


1 Answers

Pass by reference:

void sum (int &a, int &b, int &c)
like image 158
Krypton Avatar answered Feb 15 '23 11:02

Krypton