开发者

Is there a way to prove integral promotion to int?

In pure ansi C, is there any way to show that, given

char c1 = 1, c2 = 2;

the type of the following:

c1 + c2

is int?

Thanks.

NOTE: I know that accordin开发者_Go百科g to standards it is, but in C++ you can use the typeid operator to show it. I'd like to be able to show c1 + c2 is an int in C.


You can't prove a thing like that. A C compiler is allowed to replace all operations to its liking provided that the observable result is the same as in the abstract machine. You don't have direct access to the result of the adition (being an rvalue) so the type of it is not observable nor is its size, width or signedness.


How about checking using sizeof(). Didn't check it myself. Just an idea.


If c1 = 255 and x2 is 255 then when added they will add ti 510 which is too large for a char but OK for an int.

int x= c1+c2;


I know this is c++, but I wanted to use cout because it determines the type unlike printf which needs a format specifier (ie will alter your result)

char c1=156, c2=101;
cout << c2 + c1 << endl;

output is 1 there it overflows, range is only 0 to 255, CONCLUSION: it is not an int but a char


Wouldn't it be more the fact that integral promotion takes place on rvalues?

So c1 and c2 are lvalues. Only the result of c1 + c2 is a rvalue.

So the addition should be performed on char thereby causing an overflow resulting in 1.

But afterwards that rvalue of type char containing value 1 will be promoted up to a int preserving its value (in C++). So cout will see an int and output accordingly.

If cout was given a char it should output the character with the ASCII value 1 which is a non-printable character.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜