[cs13001] Example Midterm

Mikhail Nesterenko mikhail at cs.kent.edu
Tue Mar 4 00:16:49 EST 2014


> Professor Nesterenko,
> Could you please explain why this code outputs 3 5 4 5:

see below.
--
Mikhail
  	    
	       // this function accepts the parameter by value	
               int function1(int);
	       // this function accepts the paramter by reference
               int function2(int&);

               int main(){
                   int a=3, b=4;
                   int c = function1(a); // "c" is assigned
		       	   		 // incremented "a"
					 // pass-by-value does not affect "a"
					 // "c" is equal to 4
					 // "a" is equal to 3

                   int d = function2(b); // "d" is assigned 
		       	   		 // incremented "b"
					 // pass-by-reference affects "b"
					 // "d" is equal to 5
					 // "b" is equal to 5
                   cout << a << " " << b << " " << c << " " << d;
               }


	       // both functions increment the paramter
	       // since first function's parameter is pass-by-value
	       // the increment does not affect the argument
	       // since the second function's paramter is pass-by-reference
	       // the increment affects the argument

               int function1(int aa){
                   aa++;
                   return aa;
               }


               int function2(int &bb){
                   bb++;
                   return bb;
               }


More information about the cs13001 mailing list