字符类型乘以另一个字符

字符类型乘以另一个字符

本文介绍了字符类型乘以另一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C/C ++中两个字符相乘的结果的类型是什么?

unsigned char a = 70;
unsigned char b = 58;
cout << a*b << endl; // prints 4060, means no overflow
cout << (unsigned int)(unsigned char)(a*b) << endl; // prints 220, means overflow

我希望将类型T的两个数字(例如char,short,int)相乘的结果变成T.对于char,它似乎是int,因为sizeof(a*b)是4.

我编写了一个简单的函数来检查乘法结果的大小:

template<class T>
void print_sizeof_mult(){
  T a;
  T b;
  cout << sizeof(a*b) << endl;
}

print_sizeof_mult<char>()print_sizeof_mult<short>()print_sizeof_mult<int>()是4,print_sizeof_mult<long>()是8.

这些结果是否仅适用于我的特定编译器和计算机体系结构?还是在某处记录了C/C ++基本操作的输出是什么类型?

解决方案

根据C ++标准(4.5 整体促销)

和(5个表达式)

....

最后(5.6个乘法运算符)

类型charshort的转换排名小于类型int的排名.

What is the type of the result of a multiplication of two chars in C/C++?

unsigned char a = 70;
unsigned char b = 58;
cout << a*b << endl; // prints 4060, means no overflow
cout << (unsigned int)(unsigned char)(a*b) << endl; // prints 220, means overflow

I expect the result of multiplying two number of type T (e.g., char, short, int) becomes T. It seems it is int for char because sizeof(a*b) is 4.

I wrote a simple function to check the size of the result of the multiplication:

template<class T>
void print_sizeof_mult(){
  T a;
  T b;
  cout << sizeof(a*b) << endl;
}

print_sizeof_mult<char>(), print_sizeof_mult<short>(), and print_sizeof_mult<int>() are 4 and print_sizeof_mult<long>() is 8.

Are these result only for my particular compiler and machine architecture? Or is it documented somewhere that what type is the output of basic operations in C/C++?

解决方案

According to the C++ Standard (4.5 Integral promotions)

and (5 Expressions)

....

and at last (5.6 Multiplicative operators)

Types char and short have conversion ranks that are less than the rank of the type int.

这篇关于字符类型乘以另一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:48