CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Rookie query about short and byte arithmetic/bitwise ops

  1. #1
    Join Date
    Jun 2011
    Posts
    37

    Rookie query about short and byte arithmetic/bitwise ops

    VS19 16.9.688.6828
    Writing a simple C# app as an exercise to try to get my brain working after six years I hit a problem I don't recall. I ran some simple code and it seems that C# doesn't allow arithmetic and bitwise ops on 8 and 16 bit numbers viz:
    Code:
             ushort a = 0xf;
             ushort b = 0x7;
             ushort c = 0x3;
             a = b + c; // error
             a = b & c; // error
             a = a + b; // error
             a += b;    // no error
             a = (ushort)((int)a + (int)b);  // no error
    //implicit cast
             uint d = 0x1;
             d = (uint)(a + b);  // no error
             d = d + a;  // no error
    I can't believe this is a bug so can somebody please explain the thinking behind this apparent inconsistency?
    No luck finding an explanation in VS19 help!

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    19,959

    Re: Rookie query about short and byte arithmetic/bitwise ops

    It seems that the result of all these arithmetic operations with int/uint, short/ushort, byte types will be always of the type int.
    Therefore you will have to explicitly cast the result to the type you need to:
    Code:
             ushort a = 0xf;
             ushort b = 0x7;
             ushort c = 0x3;
             a = b + c; // error
             a = (ushort)(b + c);  // no error
    Victor Nijegorodov

  3. #3
    Join Date
    Jun 2011
    Posts
    37

    Re: Rookie query about short and byte arithmetic/bitwise ops

    Strange!
    I have gone back to VC# 2010 and that was the same so M.S. must know and presumably have a reason so I suppose I will have to ask them but thanks VictorN anyway.

  4. #4
    Join Date
    Feb 2017
    Posts
    606

    Re: Rookie query about short and byte arithmetic/bitwise ops

    Quote Originally Posted by RogerD View Post
    M.S. must know and presumably have a reason
    They know, and they call it the C# type promotion rules. It can give "somewhat unexpected results" mentioned here,

    https://prasadiapsara.wordpress.com/...omotion-rules/

    To avoid such problems, I prefer to use only either int or double in expressions, whichever best fits the bill. It is seldom necessary to use something else.
    Last edited by wolle; April 6th, 2021 at 12:52 AM.

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)