fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void Func(int& x, const int& y); // x CAN be changed. y cannot
  5.  
  6.  
  7. int main()
  8. {
  9. int a1 = 5, a2 = 8;
  10. cout << "a1 = " << a1 << "\ta2 = " << a2 << '\n';
  11.  
  12. // legal call
  13. Func(a1, a2);
  14. cout << "a1 = " << a1 << "\ta2 = " << a2 << '\n';
  15.  
  16. // legal call
  17. Func(a1, 20);
  18. cout << "a1 = " << a1 << "\ta2 = " << a2 << '\n';
  19.  
  20.  
  21.  
  22. // ILLEGAL call
  23. Func(20, a2);
  24. cout << "a1 = " << a1 << "\ta2 = " << a2 << '\n';
  25.  
  26.  
  27. return 0;
  28. }
  29.  
  30.  
  31. void Func(int& x, const int& y)
  32. // x CAN be changed. y cannot
  33. {
  34. x = x * 2;
  35. y = y * 2; // this is illegal
  36.  
  37. cout << "x = " << x << '\n';
  38. cout << "y = " << y << '\n';
  39. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'int main()':
prog.cpp:23:15: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
    Func(20, a2);
               ^
prog.cpp:4:6: note: in passing argument 1 of 'void Func(int&, const int&)'
 void Func(int& x, const int& y);    // x CAN be changed.  y cannot
      ^
prog.cpp: In function 'void Func(int&, const int&)':
prog.cpp:35:6: error: assignment of read-only reference 'y'
    y = y * 2;  // this is illegal
      ^
stdout
Standard output is empty