Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The code below generates the output further below. The results for int, long, long long I understand as per implicit integer arithmetic conversions however I do not understand the result of the first test i.e. to wit short as it is first promoted to int and unsigned int per its sign and then the arithmetic conversions but apparently such is not the case. Why?
import std.core;
using namespace std;

template<typename T>
void test()
{
	cout << typeid(T).name() << endl;
	make_signed_t<T> s = -1;
	make_unsigned_t<T> u = 0;
	cout << (s < u) << endl;
	cout << (s + u) << endl << endl;
}

int main()
{
	cout << boolalpha;

	test<short>();
	test<int>();
	test<long>();
	test<long long>();

	return 0;
}

short
true
-1

int
false
4294967295

long
false
4294967295

__int64
false
18446744073709551615


What I have tried:

I read cppreference i.e. to wit in particular
"If the unsigned type has conversion rank greater than or equal to the rank of the signed type, then the operand with the signed type is implicitly converted to the unsigned type."
Implicit conversions - cppreference.com[^]
Posted
Updated 4-Apr-22 21:10pm

1 solution

That happes also for signed bytes: Try to add
C++
test<char>();
to your list.

The reason is the integer promotion of both s and u (that is they are converted to int) in
C++
cout << (s < u) << endl;
cout << (s + u) << endl << endl;

from Implicit conversions - cppreference.com[^]:

Integer promotions
Integer promotion is the implicit conversion of a value of any integer type with rank less or equal to rank of int or of a bit field of type _Bool, int, signed int, unsigned int, to the value of type int or unsigned int

If int can represent the entire range of values of the original type (or the range of values of the original bit field), the value is converted to type int. Otherwise the value is converted to unsigned int.

Integer promotions preserve the value, including the sign:
 
Share this answer
 
Comments
BernardIE5317 5-Apr-22 3:30am    
Thank You
CPallini 5-Apr-22 11:37am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900