0
double diff = static_cast<int64_t>(a- b);

a and b are of type int64_t.

I saw this code in our project. I think it is suspicious, but I am really not sure. I am familiar with static_cast, and I would not write code like this.

Is this static_cast valid/legit? Is it useful?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
BufBills
  • 8,005
  • 12
  • 48
  • 90
  • 2
    What types are `a` and `b`? – David Schwartz Oct 07 '13 at 19:41
  • This code looks weird; there's no point in that cast. – Oliver Charlesworth Oct 07 '13 at 19:42
  • It does seem odd to cast something to an `int64` only to assign it to a `double`. Maybe not "wrong", but "odd". Does your compiler throw any warnings when you use `-Wall -pedantic`? And now that we know `a` and `b` are already of byte `int64_t`, another cast ought to do nothing... Looks like some "left over" code that should have been cleaned out a long time ago. – Floris Oct 07 '13 at 19:42
  • The `static_cast(value)` notation is C++ only. It is invalid in C. Retagging. – Jonathan Leffler Oct 07 '13 at 19:43
  • If `a` and `b` are already `int64_t`s then the `static_cast` is indeed pointless. – Simple Oct 07 '13 at 19:49
  • If your compiler has an `int` larger than 64 bit, integral promotion is applied to `a` and `b`, converting them to `int`s. The `static_cast` then would narrow the result down to the range of `int64_t`, invoking UB (signed integer over-/underflow). – dyp Oct 07 '13 at 19:52
  • @DyP: I suppose that's possible, but I've never heard of a system having a native `int` type wider than 64 bits. It's much more likely that the author of this code intended to write `static_cast` rather than guard against an out-of-range error on such an arcane system. – Adam Rosenfield Oct 07 '13 at 19:55

2 Answers2

1

If a and b are both int64_t, there is no point to the cast. It is casting a result of type int64_t to type int64_t. It would be like doing this:

int a = 10, b = 5;
double c = (int)(a - b); // the cast is not needed, but also not "harmful"
Zac Howland
  • 15,777
  • 1
  • 26
  • 42
0

This cast is valid but does not do anything. I agree that it is suspicious. You should carefully review what the code is supposed to be doing, and if it's correct then you may want to re-write it so that the intent is clearer and so that it doesn't look as suspicious.

bames53
  • 86,085
  • 15
  • 179
  • 244