Can a constant be passed to a reference

Why does this code work, even though we are passing a constant to a reference?

#include <iostream.h>

int fun(int a, int &b)
{
a+=b;
b=b%3;
cout<<"a= "<<a<<" and b= "<<b<<"\n";
return b-a;
}

void main()
{
int x=14;
int y=fun(x,2);
cout<<"x= "<<x<<" and y= "<<y<<"\n";
}
is there a difference between
1
2
3
const int a = 2;
//and
2;

??
Can you pass a by reference??
It shouldn't have worked, or at least properly.
The output is coming as:
a=16 and b=2
x=14 and y=-14
and is it wrong?
May I ask what compiler you are using? Honestly, you can't pass const as references, since they don't really have a reference point.

After this post
is there a difference between
1
2
3
const int a = 2;
//and
2;

??
Can you pass a by reference??

I assumed vinitadhawan answered NO to himself, got the error
1
2
3
error:invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
  int y = fun(x,2);
                ^                   

removed the '&' in the prototype and go the output he has.
Last edited on
no, i have got the above output with the mentioned code itself and i am using TurboC 4.5
@shadowCODE is right, gcc Compiler complains during the compilation the error he mentioned in his comment.

I have some more comments on the code, why main function is void? main in c++ must have return type of int as a return type, this is most important. Please correct me is if I am wrong.
http://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c
There is some post there about the prototype of main with reference to Standard C and Standard C++
He is using Turbo C, which is super old, and I think doesn't have proper error checking. It doesn't use int main, but void main. I HIGHLY recommend you use something newer. Turbo C++ seems to not have been supported since 2006. Why not use Visual C++ or Dev C++ if you are on windows, or some equivalent if you are using Linux (I hear people like Code::Blocks on Linux). Thank, Spike.
I recommend Visual C++
I am seeking the answer to my basic question - why is the above code working? I know that newer compiler are available and TuboC 4.5 is an old compiler but does that mean that the above code is running due to a compiler problem?
> does that mean that the above code is running due to a compiler problem?

Yes, it is non-conforming with respect to this. Which is not surprising; the first International Standard for C++ came a few years after this compiler was released.
Topic archived. No new replies allowed.