Find the answer to your Linux question:
Results 1 to 5 of 5
void SampleFun(int&); void SampleFun1(int&); void TestFun(int*); void main() { int x = 500; int*y; y = &x; TestFun(y); } void TestFun(int* a) { SampleFun((int)*a); SampleFun1((int&)*a); } void SampleFun(int& val) { ...
  1. #1
    Just Joined!
    Join Date
    Dec 2009
    Location
    India
    Posts
    2

    Smile C++ build error

    void SampleFun(int&);
    void SampleFun1(int&);
    void TestFun(int*);
    void main()
    {

    int x = 500;
    int*y;
    y = &x;
    TestFun(y);
    }
    void TestFun(int* a)
    {
    SampleFun((int)*a);
    SampleFun1((int&)*a);
    }
    void SampleFun(int& val)
    {
    val= 1000;
    }
    void SampleFun1(int& val)
    {
    val= 22222;
    }


    SampleFun((int)*a); is not working in linux
    SampleFun1((int&)*a); is ok

    but both are working in windows


    Thanks in advance

  2. #2
    Linux User
    Join Date
    Jan 2006
    Posts
    414

  3. #3
    Linux Enthusiast KenJackson's Avatar
    Join Date
    Jun 2006
    Location
    Maryland, USA
    Posts
    506
    This is a value: (int)*a
    You are trying to pass it by reference.

    Are you saying a windows C++ compiler compiles that without an error? Which compiler?

    BTW, if you click on the asterisk, #, you'll get a pair of code tags. If you put your code between them it will look a lot nicer and will make it easier for people to help you.

  4. #4
    Just Joined!
    Join Date
    Dec 2009
    Location
    India
    Posts
    2

    Smile c++ build error in linux

    Hai KenJackson,

    Iam using visual studio 2008. Why it doesnt give any error,

    As you said (int)*a is value, then what is (int&)*a .


    Thank you for the comments....

  5. #5
    Linux Enthusiast KenJackson's Avatar
    Join Date
    Jun 2006
    Location
    Maryland, USA
    Posts
    506
    (int&)*a is a reference to the object that a points to.

    Apparently what Visual C++ is doing is making a local copy of the value and passing a reference to it to function SampleFun(). That would obviously work, but it could circumvent the intent since data is often passed by reference so that it can be modified. If you modify a temporary copy, the change is lost when the function returns.

    Let me put in a plug against ever using "&" in a declaration. I wish it were not part of the language.

    When you look at a call to SampeFun(), you don't know that it is passing by reference unless you look a the declaration, which could be in some header that's buried by multiple inclusions. And if it modifies a variable that you though you were passing by value, you have a bug.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...