CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9

Threaded View

  1. #8
    Join Date
    Apr 1999
    Posts
    27,449

    Re: have en error: expression must have integral or enumtype

    Quote Originally Posted by f0rumh4x View Post
    Is there one specific resource that would be a good reference for understanding floating point better that I can be directed to.
    Well, all you would need to know in a general sense is that floating point arithmetic is not exact, unless you're adding/subtracting negative powers of 2.

    Here is a good example of a loop that uses floating point, where you can get in trouble:
    Code:
    for (double d = 0.0; d < 1.0; d += 0.01)
    { }
    If that loop is allowed to be executed, how many times will that loop execute? If you use an answer based on adding exactly 0.01 to d, then you may be right -- or you may be wrong. Not only that, you may be right if certain compiler switches are used to build the program, but for another set of compiler switches, the very same code produces a different answer.

    The issue is that decimal 0.01 is not an exact binary floating point number. It is a repeating, non-terminating binary floating point number. So you have a non-repeating decimal fraction being translated into a repeating, non-terminating binary floating point number. Those bits on the far end of the binary number start to propagate, causing round-off error. So when you add 0.01 to d, the value of "d" may be off just enough to remove an iteration from, or add an iteration to the loop.

    http://www.parashift.com/c++-faq/floating-pt-errs.html
    http://www.parashift.com/c++-faq/flo...int-arith.html
    http://www.parashift.com/c++-faq/flo...nt-arith2.html

    Also, there is a security site that has identified code like the loop above as a security risk. Since it is indeterminate as to the number of times the loop will execute, the code is considered flawed.

    The bottom line is that for loop indices, always strive to use integer loop indices so you know for sure how many times the loop is to be executed. To make sure of this, it may require a simple change (divide by 10 or 100, 1000, etc. within the loop), or the solution may be more elaborate. But whatever the solution, the loop indices are to be integer to ensure how many times a loop will execute.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; March 21st, 2013 at 05:31 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured