Static Analysis Tooling / Effective D

Marco Leise via Digitalmars-d digitalmars-d at puremagic.com
Wed Apr 23 19:56:54 PDT 2014


Am Tue, 21 Jan 2014 04:34:56 +0000
schrieb "Brian Schott" <briancschott at gmail.com>:

> There's a small feature wishlist in the project's README, but I'd 
> like to get some opinions from the newsgroup: What kinds of 
> errors have you seen in your code that you think a static 
> analysis tool could help with?

Yes, this one:

size_t shiftAmount = 63;
[…]
auto x = 1 << shiftAmount;

The trouble is that auto will now resolve to int instead of
size_t as indicated by the type of shiftAmount. Sure, my fault
was to use an innocent »1« instead of »cast(size_t) 1«. So the
result is:

int x = -2147483648;

But »1 << size_t« doesn't always yield an int result! Compare to
this:

size_t x = 1 << shiftAmount;

which becomes:

size_t x = 18446744071562067968;


Two possible warnings could be:
- Shifting an »int« by a »size_t« is not the correct way to
  enforce a »size_t« result. Please use
  »cast(size_t) 1 << shiftAmount« if that was the intention.
- »auto« variable definition will resolve to »int« and may
  lose information from expression »1 << shiftAmount«. Please
  replace »auto« with »int« if that is what you want or set
  the correct data type otherwise.

In both cases an explicit mention of a data type resolves the
ambiguity.

-- 
Marco



More information about the Digitalmars-d mailing list