Wrong result with enum

Patrick Schluter Patrick.Schluter at bbox.fr
Thu Nov 11 13:11:01 UTC 2021


On Thursday, 11 November 2021 at 05:37:05 UTC, Salih Dincer wrote:
> is this a issue, do you need to case?
>
> ```d
> enum tLimit = 10_000;  // (1) true result
> enum wLimit = 100_000; // (2) wrong result
>
> void main()
> {
>   size_t subTest1 = tLimit;
>   assert(subTest1 == tLimit);        /* no error */
>
>   size_t subTest2 = wLimit;
>   assert(subTest2 == wLimit);        /* no error */
>
>   size_t gauss = (tLimit * (tLimit + 1)) / 2;
>   assert(gauss == 50_005_000);       /* no error */
>
>   gauss = (wLimit * (wLimit + 1)) / 2;
>   assert(gauss == 5_000_050_000);    /* failure
>
>   // Fleeting Solution:
>     enum size_t limit = 100_000;
>     gauss = (limit * (limit + 1)) / 2;
>     assert(gauss == 5_000_050_000); //* no error */
>
> } /* Small Version:
>
> void main(){
>   enum t = 10_000;
>   size_t a = t * t;
>   assert(a == 100_000_000);    // No Error
>
>   enum w = 100_000;
>   size_t b = w * w;
>   assert(b == 10_000_000_000); // Assert Failure
> }
> */
> ```

Integer overflow. By default an enum is defined as `int` which is 
limited to 32 bit. `int.max` is 2_147_483_647 which is the 
biggest number representable with an int.

You can declare the enum to be of a bigger type `enum  : long { w 
= 100_000 };`
or you can use `std.bigint` if you don't know the maximum you 
work with or the library `std.experimental.checkedint` which 
allows to set the behaviour one wants in case of overflow.


More information about the Digitalmars-d-learn mailing list