我们可以在C和C ++的表达式左侧使用函数吗?

在C语言中,我们不能在表达式的左侧使用函数名。在C ++中,我们可以像这样使用它。这可以通过一些返回引用变量的函数来完成。

C ++函数可以像返回指针一样以类似的方式返回引用。

当一个函数返回一个引用时,它返回一个隐式的指向其返回值的指针。这样,可以在赋值语句的左侧使用函数。例如,考虑这个简单的程序-

示例

#include <iostream>
#include <ctime>
using namespace std;
double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0};
double& setValues( int i ) {
   return vals[i]; // return a reference to the ith element
}
//主函数调用上面定义的函数。
int main () {
   cout << "Value before change" << endl;
   for ( int i = 0; i < 5; i++ ) {
      cout << "vals[" << i << "] = ";
      cout << vals[i] << endl;
   }
   setValues(1) = 20.23; // change 2nd element
   setValues(3) = 70.8; // change 4th element
   cout << "Value after change" << endl;
   for ( int i = 0; i < 5; i++ ) {
      cout << "vals[" << i << "] = ";
      cout << vals[i] << endl;
   }
   return 0;
}

输出结果

Value before change
vals[0] = 10.1
vals[1] = 12.6
vals[2] = 33.1
vals[3] = 24.1
vals[4] = 50
Value after change
vals[0] = 10.1
vals[1] = 20.23
vals[2] = 33.1
vals[3] = 70.8
vals[4] = 50

返回引用时,请注意所引用的对象不会超出范围。因此,返回对本地var的引用是不合法的。但是您始终可以返回静态变量的引用。

int& func() {
   int q;
   //!返回q; //编译时错误
   static int x;
   return x; // Safe, x lives outside this scope
}