0

I wrote the following lines in C#

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
        extern static uint _controlfp(uint newcw, uint mask);

        const uint _MCW_EM = 0x0008001f;
        public const uint EM_INVALID = 0x00000010;
        public const uint EM_DENORMAL = 0x00080000;
        public const uint EM_ZERODIVIDE = 0x00000008;
        public const uint EM_OVERFLOW = 0x00000004;
        public const uint EM_UNDERFLOW = 0x00000002;
        public const uint EM_INEXACT = 0x00000001;

        static void MaskFpu(uint pExceptionMask = EM_INVALID)
        {
            // add desired values
            _controlfp(_MCW_EM, pExceptionMask);
        }

        static void Main(string[] args)
        {
            MaskFpu(EM_ZERODIVIDE);

            int a = 0;
            var b = 5/a;

            Console.WriteLine("b = " + b);
        }
    }
}

The Main method starts by setting the control word. Obviously I want DivideByZeroExceptions to be masked.

After performing _controlfp I would expect that a division by zero would return NaN. but var b = 5 / a raises an exception instead.

How can I truely keep my process from raising DivideByZeroExceptions?

Florian Grummel
  • 332
  • 3
  • 14
  • If you actually just used floating point types in your test, you wont need any of this error-prone legacy junk. Try it. – leppie Jun 02 '15 at 09:23
  • 1
    I would expect `controlfp` to control *floating-point* operations - you're performing integer operations. Try using `0.0` or `5.0` and see if that helps you... – Jon Skeet Jun 02 '15 at 09:23
  • 1
    Maybe [this](https://msdn.microsoft.com/en-us/library/aa261190%28v=vs.60%29.aspx) will help: _"Divide-by-zero exceptions can subsequently be disabled by calling _ _controlfp(EM_ZERODIVIDE, EM_ZERODIVIDE)"_ – DGibbs Jun 02 '15 at 09:27
  • thank you for the response. Indeed the mask works if I replace `int` by `double`. Unfortunately your recommendation does not work for my example, DGibbs. :( – Florian Grummel Jun 02 '15 at 09:41

1 Answers1

0
int a = 0;
var b = 5/a;

You are performing integer arithmetic here and so masking floating point exceptions has no effect on this expression.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490