matt
matt

Reputation: 4244

MSVC++ erroring on a divide by 0 that will never happen! fix?

const int bob = 0;

if(bob)
{
    int fred = 6/bob;
}

you will get an error on the line where the divide is done: "error C2124: divide or mod by zero"

which is lame, because it is just as inevitable that the 'if' check will fail, as it is the divide will result in a div by 0. quite frankly I see no reason for the compiler to even evaluate anything in the 'if', except to assure brace integrity.

anyway, obviously that example isn't my problem, my problem comes when doing complicated template stuff to try and do as much at compile time as possible, in some cases arguments may be 0.

is there anyway to fix this error? or disable it? or any better workarounds than this:

currently the only work around I can think of (which I've done before when I encountered the same problem with recursive enum access) is to use template specialization to do the 'if'.

Oh yeah, I'm using Visual Studio Professional 2005 SP1 with the vista/win7 fix.

Upvotes: 9

Views: 2227

Answers (3)

MSalters
MSalters

Reputation: 179779

The problem - and the compiler has no choice in this - is that bob is a Integral Constant Expression, as is 6. Therefore 6/bob is also an ICE, and must be evaluated at compile time.

There's a very simple solution: inline int FredFromBob(int bob) { return 6/bob; } - a function call expression is never an ICE, even if the function is trivial and declared inline.

Upvotes: 3

Gary
Gary

Reputation: 5732

Can you provide more detail on what you're trying to do with templates? Perhaps you can use a specialised template for 0 that does nothing like in the good old Factorial example and avoid the error altogether.

template <int N>
struct Blah 
{
    enum { value = 6 / N };
};

template <>
struct Blah<0> 
{
    enum { value = 0 };
};

Upvotes: 3

Ferdinand Beyer
Ferdinand Beyer

Reputation: 67127

I suppose your compiler tries to optimize the code snippet since bob is defined const, so that the initial value of fred can be determined at compile time. Maybe you can prevent this optimization by declaring bob non-const or using the volatile keyword.

Upvotes: 4

Related Questions