Confusion about int type

Discussion in 'C++' started by techme, Mar 22, 2010.

  1. techme

    techme New Member

    Joined:
    Feb 15, 2010
    Messages:
    86
    Likes Received:
    0
    Trophy Points:
    0
    I ever thought int is the simplest type, indeed it is much more complicated that what I imagined....

    Please help me with following code.

    Code:
    #include <iostream>
    using std::cout;
    using std::endl;
    
    // calculate power
    template <class T>
    T mypower(const T& x, const int& n){
    	if (n==0)
    		return 1;
    	else
    		return x*mypower(x,n-1);
    }
    
    int main()
    {
    	int x=2.5;
    	int n=5;
    	cout << x << "^" << n << " = " << mypower(x,n) << endl;
    	return 0;
    }
    My questions (confusions):

    (1) I know generally if we use reference parameters (x and n) for a function and do not change them, we shall use 'const' for them. However, if I purposely remove const, I found it is ok to use 'T& x '. However, using 'int &n' caused following error

    Why removing const works for template type T but not for int? I checked it also works for double type. What makes int type so special?


    (2) For template type T& x, if I use

    Code:
    int x =2;
    not problem. So, when not using const, why 'int & n' does not work, but T& x with T=int works?


    Please help me with these confusions.
     
  2. creative

    creative New Member

    Joined:
    Feb 15, 2010
    Messages:
    87
    Likes Received:
    0
    Trophy Points:
    0
    This has nothing to do with int specifically, and everything to do with temporaries. You're passing the expression "n-1" into the second argument recursively; this expression evaluates to an rvalue temporary.

    Temporaries only have a value; they do not correspond to any particular location in memory. Therefore, they cannot be bound to a reference! But, because it's convenient to allow it, you can bind them to a const reference and things will work as expected. When you pass an rvalue by const reference, the behavior is essentially similar to pass-by-value, except that the constructor used will not necessarily be the copy constructor
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice