Uploaded image for project: 'Swift'
  1. Swift
  2. SR-5964

dividedReportingOverflow may fail to compile for calculations that overflow

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Compiler, Standard Library
    • Labels:
      None
    • Environment:

      macOS 10.12.6

      Xcode 9.0 (9A235)

      Apple Swift version 4.0 (swiftlang-900.0.65 clang-900.0.37)
      Target: x86_64-apple-macosx10.9

      Description

      The documentation of 

      public func dividedReportingOverflow(by rhs: Self) -> (partialValue: Self, overflow: Bool)
      

       from the FixedWidthInteger protocol states that overflows are indicated by a flag in the return value, and that dividing by zero is not an error.

      However, it may fail to even compile in cases where the compiler already detects an overflow or division by zero: 

      // main1.swift
      do {
          let minusOne = -1
          let r1 = Int.min.dividedReportingOverflow(by: minusOne)
          print(r1)
          
          let zero = 0
          let r2 = Int.min.dividedReportingOverflow(by: zero)
          print(r2)
      }
      

       

      $ swiftc main1.swift 
      main1.swift:7:19: error: division by zero
              let r2 = Int.min.dividedReportingOverflow(by: zero)
                               ^
      main1.swift:3:19: error: division '-9223372036854775808 / -1' results in an overflow
              let r1 = Int.min.dividedReportingOverflow(by: minusOne)
      

       

      If the same code is on top-level then it compiles and runs as expected:

      // main2.swift
      let minusOne = -1
      let r1 = Int.min.dividedReportingOverflow(by: minusOne)
      print(r1)
      
      let zero = 0
      let r2 = Int.min.dividedReportingOverflow(by: zero)
      print(r2)
      

       

      $ swiftc main2.swift && ./main2 
      (partialValue: -9223372036854775808, overflow: true)
      (partialValue: -9223372036854775808, overflow: true)

       

       

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              moiseev Max Moiseev
              Reporter:
              martin Martin
              Votes:
              1 Vote for this issue
              Watchers:
              10 Start watching this issue

                Dates

                Created:
                Updated: