This topic has been archived. It cannot be replied.
工作学习 / IT技术讨论 / what's the value of K? why?
-hannibal(汉尼拔);
2001-8-10{188}(#162751@0)
long & inc (long &i)
{
i = i + 1;
return i;
}
main ()
{
long j = 0;
int k = 0;
inc (j);
inc (k);
}
what's the value of K? why?
2?
-bigdesk(NightLight);
2001-8-11(#163187@0)
no, should be 0. think about it, why 0?
-hannibal(汉尼拔);
2001-8-11(#163297@0)
0, type dismatch, a temporary variable will be used. So the return value of inc(k) is assigned to the temporary variable and disappears after the call finished
-flipflop(翻云覆雨);
2001-8-11(#163300@0)
sry, not return value, the assign statement in inc()
-flipflop(翻云覆雨);
2001-8-11(#163313@0)
Actually, this is a wrong program. It can not pass compiling since k is an int and it can not pass to inc function which parameter is long &.
-xiliu(xiliu72);
2001-8-11(#163325@0)
yes you are correct. but I wonder under some old compiler it works
-hannibal(汉尼拔);
2001-8-11(#163329@0)
If so, I think k is 1.
-xiliu(xiliu72);
2001-8-11(#163330@0)
why 1?
-hannibal(汉尼拔);
2001-8-11(#163333@0)
No, it will pass, almost all compilers can automatically cast the wrong type to correct one if it's possible
-flipflop(翻云覆雨);
2001-8-11(#163334@0)
and there will be a warning msg for sure
-flipflop(翻云覆雨);
2001-8-11(#163339@0)
at least VC++6.0 does not. I always feel MS applies the restrictest way
to it's C++ compiler on normal issues
-hannibal(汉尼拔);
2001-8-11(#163340@0)
Yes, u r right. I think I made a mistake, it's not a real "cast", since the parameter is passed by reference
-flipflop(翻云覆雨);
2001-8-11(#163346@0)
I'm sorry. this example only works when compiler contructs temp object
and casts it to corresponding reference. does any compliler do that?
-hannibal(汉尼拔);
2001-8-11(#163355@0)
As u said, I think under some old compilers it will work. Or maybe C++ Builder?
-flipflop(翻云覆雨);
2001-8-11(#163357@0)
some on unix platform
-hannibal(汉尼拔);
2001-8-11(#163359@0)
Yes. In some sense, you area right. VC can also do this. int can transfer to long. But it is really wrong to tranfer int to long &.
-xiliu(xiliu72);
2001-8-11(#163369@0)