1

Is it possible to enable warnings in g++ or clang on cast from int to int64_t? Example:

int n;
cin >> n;
int64_t power = (1 << n);

I want that compiler tells me about this conversion in third line.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Sukhanov Niсkolay
  • 1,298
  • 1
  • 12
  • 26
  • Why do you wan't a warning on an upcast? – NathanOliver May 13 '16 at 15:49
  • The third statement is not syntactically valid, could you correct it please? – Bathsheba May 13 '16 at 15:50
  • 1
    I assume you want the warning because `(1LL << n)` is what you actually want. – Martin York May 13 '16 at 15:53
  • @NathanOliver, look for Loki Astari comment. This is a common mistake. When you write something like `int64_t memory_size = 2 * 1024 * 1024 * 1024;` and get overflowing. But in this case it will give you a warning, but in that case in the post - no warning. – Sukhanov Niсkolay May 13 '16 at 15:55
  • @LokiAstari, yes, exactly! – Sukhanov Niсkolay May 13 '16 at 15:56
  • 2
    Because it happens in so many places automatically a warning flag like that would generate a lot of noise. So I don't think it would be useful in the general case. So I don't believe there is one (I did try and google but nothing useful came up). You could create your own class to catch it I suppose. – Martin York May 13 '16 at 16:03

1 Answers1

2

You could build something on these lines:

struct my_int64
{
    template<class Y> my_int64(const Y&)
    {
        static_assert(false, "can't do this");
    }
    template<> my_int64(const long long&) = default;
    /*ToDo - you need to hold the data member here, and 
      supply necessary conversion operators*/
};

Then

int n = 3;
my_int64 power = (1LL << n);

compiles, but

my_int64 power = (1 << n);

will not. In that sense, this is a good starting point. You could hack the preprocessor to use this in place of int64_t.

If you wanted a warning rather than an error, you could replace the static_assert with

my_int64 x{}; Y y = x; and hope the compiler emits a warning for a narrowing conversion, and trust it to optimise out the two statements as they are collectively a no-op.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Yes, I like the idea. But probably static_assert isn't what I looking for, because I want just warning. – Sukhanov Niсkolay May 13 '16 at 16:10
  • @SukhanovNiсkolay _"because I want just warning"_ Dude you are picky. I'm afraid you'll need to rewrite `static_assert()` to something like `static_assertion_warn()` that results in a compiler warning only. Have fun with that. – πάντα ῥεῖ May 13 '16 at 16:14
  • 2
    OK. It's a Friday. Pasted an idea up for that. – Bathsheba May 13 '16 at 16:15
  • 1
    @SukhanovNiсkolay Here's some [more info](http://stackoverflow.com/questions/8936063/does-there-exist-a-static-warning) ... Was easy to find it :-P ... – πάντα ῥεῖ May 13 '16 at 16:32