c++visual-c++modulofractionscmath

How to avoid using temporary variable with std::modf?


I've recently run into an issue where I got a segfault in MSVC where I wouldn't in GCC.

After hours I realized that apparently my version of MSVC does not support the following syntax:

double value = 3.4;
double fractional = std::modf(value, nullptr);

where I don't want/care about the whole part of the number.

Yes, I know I could do "3.4 - 3.0" or the like, but I'm concerned about specifically using modf in this way. Currently I can only see doing this via:

double temp; 
double value = 3.4;
double fractional = std::modf(value, &temp);

Is there a way around this temporary variable?


Solution

  • If you do not need value afterwards you could call it as

    double value = 3.4;
    double fractional = std::modf(value, &value);
    

    If you then still need the original value, you could reconstruct it easily.

    PS: I did not find any mention of nullptr being a valid parameter. Maybe MSVC is right in going havoc.

    PS2: I would not worry too much about the unecessary temporary. I would expect the compiler to generate similar code and explicitly mentioning the temporary is much cleaner and more readable as compared to passing value merely to avoid the temporary.