函数中的引用不会更改函数外部的项。C++

Reference in the function doesn't change item outside of it. C++

本文关键字:函数 外部 C++ 引用      更新时间:2023-10-16

试图通过引用从函数中获取值,但似乎我一直在获取函数调用之前分配的值。

void third()
{
    int summ = mainInput(3);
    int second = 0;
    cout << "You should pay " << fiveBill(summ, second) << second;
}
int fiveBill(int summ,int &two)
{
    int five=0;
    if (summ%2==0)
    {
        two = summ / 2;
    }
    else
    {
        two = (summ - 5) / 2;
        five++;
    }
    while (two>4)
    {
        two -= 5;
        five += 2;
    }
    return five;
}

变量"second"在我调用它时一直显示为0,而我确信它在函数内发生了变化。

在c++中,函数调用参数求值的顺序是故意不指定的。编译器完全有可能在计算对fiveBill(summ, second)的调用之前将second作为<<的参数进行计算。只需在单独的先验表达式中调用fiveBill,或将输出拆分为两个表达式。