Should unreachable code be considered an error?

Michel Fortin michel.fortin at michelf.com
Wed Aug 24 18:41:35 PDT 2011


On 2011-08-22 21:27:39 +0000, Stewart Gordon <smjg_1998 at yahoo.com> said:

> On 20/08/2011 07:28, Bernard Helyer wrote:
>> On Sat, 20 Aug 2011 01:42:56 +0100, Stewart Gordon wrote:
>> 
>>> So essentially you're looking to catch cases where, if you consider the
>>> function as a flow chart, there is no chain of arrows from the start of
>>> the function to the statement in question.  That should be
>>> straightforward.  But you're not worrying about catching cases where
>>> some arrow would never be followed.  Have I got that right?
>> 
>> Pretty much, minor correction on the last part -- an arrow means that the
>> compiler considers it a possibility, so it's not considered in so far as
>> the data structure doesn't make the distinction.
> 
> That's more or less what I meant.  The compiler can't identify all 
> arrows that will never be followed - this would mean solving the 
> halting problem.  So it takes the view that any arrow _may_ be 
> followed.  But if there's no arrow at all leading to a statement, the 
> compiler can easily see that it's unreachable and so issue a 
> warning/error.

But what about templates? Take this pretty reasonable function template:

	bool frontEquals(R, V)(R range, V value)
	{
		if (range.empty)
			return false;
		else
			return range.front == value;
	}

This will work fine with most ranges, but if you encounter an infinite 
range (with empty defined as "enum empty = false") then the "return 
false" statement becomes unreachable and you'll get an error/warning? 
It doesn't make sense.

Or perhaps we should require the above to be written like this:

	bool frontEquals(R, V)(R range, V value)
	{
		static if (!range.isInifinite)
			if (range.empty)
				return false;
		
		return range.front == value;
	}

But isn't that messy? And I'm dealing with only one possibility here… 
what if a range was always empty? Something else to care about. 
Thankfully I'm only checking a boolean property limited to two values.


-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/



More information about the Digitalmars-d mailing list