×

Loading...

Topic

This topic has been archived. It cannot be replied.
  • 工作学习 / IT技术讨论 / what's the value of K? why?
    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?
      • no, should be 0. think about it, why 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
      • sry, not return value, the assign statement in inc()
    • 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 &.
      • yes you are correct. but I wonder under some old compiler it works
        • If so, I think k is 1.
          • why 1?
      • No, it will pass, almost all compilers can automatically cast the wrong type to correct one if it's possible
        • and there will be a warning msg for sure
        • at least VC++6.0 does not. I always feel MS applies the restrictest way to it's C++ compiler on normal issues
          • Yes, u r right. I think I made a mistake, it's not a real "cast", since the parameter is passed by reference
            • I'm sorry. this example only works when compiler contructs temp object and casts it to corresponding reference. does any compliler do that?
              • As u said, I think under some old compilers it will work. Or maybe C++ Builder?
                • some on unix platform
        • 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 &.