Reputation: 42534
The following code gives the error error C2397: conversion from 'int' to 'ushort' requires a narrowing conversion
when compiled with Visual Studio 2015.
typedef unsigned short ushort ;
struct MyStruct{ ushort a ;} ;
MyStruct func(){
ushort a = 1, b = 1 ;
ushort c = a | b ; // <--- No error here
//return {c} ; // <--- Compiles fine
return {a | b} ; // <--- Error in this line
}
int main(){
ushort a = func().a ;
}
The expression a | b
seems to return an int
in one case and a ushort
in another.
I can't make sense of this.
Can you explain what's happening here?
PS: Exact compiler version: Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
Upvotes: 0
Views: 65
Reputation: 1530
In case of arithmetic operations on ushort, the operands are converted to a type which can hold all values. So that overflow can be avoided. Operands can change in the order of int, uint, long and ulong. Please see the C# Language Specification In this document go to section 4.1.5 Integral types (around page 80 in the word document). Here you will find:
For the binary +, –, *, /, %, &, ^, |, ==, !=, >, <, >=, and <= operators, the operands are converted to type T, where T is the first of int, uint, long, and ulong that can fully represent all possible values of both operands. The operation is then performed using the precision of type T, and the type of the result is T (or bool for the relational operators). It is not permitted for one operand to be of type long and the other to be of type ulong with the binary operators.
Solution:
Use int, uint, long, ulong
Upvotes: -2