What does Coverity/clang static analysis actually do?
Christopher Wright
dhasenan at gmail.com
Sat Oct 3 05:22:24 PDT 2009
Nick Sabalausky wrote:
> static void Main(string[] args)
> {
> Foo f;
> if(args.Count() > 2) { f = new Foo(); }
>
> if(args.Count() > 2)
> {
> f.bar(); // ERROR: Use of unassgned local variable 'f'
> }
>
> Foo f2;
> createFoo(ref f2); // ERROR: Use of unassgned local variable 'f2'
> f2.bar();
> }
>
> static void createFoo(ref Foo f)
> {
> f = new Foo();
> }
> ---------------------------------------------
>
> The first one is rather strange coding though and makes it easy to hide
> errors anyway. And the second one's a tad odd too, plus I don't see any harm
> in solving that with "Foo f2=null": it would at least be a hell of a lot
> better than the compiler doing that very same "=null" automatically. I know
> Walter doesn't agree, but I'd much rather have a few slightly inconvinient
> false positives (or would it really be a false negative?) than even a mere
> possibility for a hidden error.
The second one is an error; createFoo might use its argument before
assigning. You should have marked its argument as out instead, which
would not yield an error.
In point of fact, that's a common pattern in C#. Dictionaries define a
method bool TryGetValue(key, out value):
DateTime date;
if (dict.TryGetValue("key", out date))
{
// use date
}
More information about the Digitalmars-d
mailing list