Eiffel "Gotchas"


Oops!

Gotcha #2 - Answer and Explanation

Here's the question again:

In what context can the "check" instruction in this code fragment fail? (Don't worry about exceptional conditions like "out of memory".)

   s: STRING
   ...
   s := "gotcha"
   check
      s.count = 6
   end

Manifest string constants are not constant on some compilers. For example, ISE Eiffel uses the same copy of "gotcha" each time, whilst Visual Eiffel generates a new one each time. Here's some code that can cause the "check" instruction to fail:

   class MAIN
   
   creation make
   
   feature {ANY}
   
      make is
         local
            i: INTEGER
            s: STRING
         do
            from
               i := 1
            variant 3 - i
            until i > 2 loop
               s := "gotcha"
               check
                  s.count = 6
               end
               s.remove(1) -- removes the first character
               i := i + 1
            end
         end
   
   end
The workaround is to change s := "gotcha" to s := clone("gotcha")

ETL 2nd printing p386 says "A constant expression has a value which does not change at run time, and is the same for all instances of a class." But p391 makes it clear that a manifest string constant is a constant reference to a changeable string.

This suggests that Visual Eiffel's safer implementation is (strictly speaking) non-conforming.


Eiffel and NICE are registered trademarks of the Nonprofit International Consortium for Eiffel.

Eiffel "Gotchas"