开发者

What kind of type conversions are explicitly redundant according to the standard?

开发者 https://www.devze.com 2023-01-10 19:47 出处:网络
I\'m confused about the rules concerning this matter [a good URL might save time in answering]. I notice that a lot of the time conversion implicitly works but other times it\'s required.

I'm confused about the rules concerning this matter [a good URL might save time in answering]. I notice that a lot of the time conversion implicitly works but other times it's required.

e.g. I had expected it to work:

long long a;
int b;
[..]
a = b * 1000;

but it turns out, 'a' overflows and it's required to

a = (long long) b * 1000;

That was peculiar since 'a' being the 'big one' I had expected it would bother.

Anyway, apart from that example, do you know a comprehensive source of information on the matter? No 'most of the time is ok', that gets me paranoid.

EDIT: Is it only a matter of 'the second part does the calculation first and there it overflows, follow that rule closely'?

EDIT2: If ther开发者_如何学Pythone is a calculation such as

long long a;
int b;
short c;
[..]
c = b + a * 3;

, would doing

c = b + (int) a * 3; 

ensure proper conversion?

or would it need

c = (short) b + (int) a * 3; 

or, would it be enough to

c = (short) b + a * 3; 


Type conversions works step by step. Your expression can be viewed as

a = (b * 1000);

in the b * 1000, the compiler (let's pretend it's stupid) doesn't know you are going to store it into a long long. Since both b and 1000 are ints, the result will be an int also. How big a is doesn't matter here.

You could avoid the cast by making 1000 a long long.

a = b * 1000LL;

Edit: For your edit 2:

  • a is a long long, b is an int, 3 is an int.
  • Therefore, a * 3 is a long long
  • Therefore, b + a*3 is a long long
  • But a cast is not needed in c = b+a*3, as a arithmetic operands are implicitly convertible to each other.
0

精彩评论

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

关注公众号