Jason Kim
Jason Kim

Reputation: 19051

Storing double value in the place of unsigned int

See these lines in the program:

if (ftPtr) {
    *ftPtr = feet;
}

Note that feet contains double value as a result of modf(). On the other hand ftPtr is an address for an unsigned int variable.

Question Now this program runs fine without any warning, but it leaves a bad taste in my mouth that double value is assigned to int variable. Is assigning double value to int variable using its address kosher in C?

#include <stdio.h>
#include <math.h>

void metersToFeetAndInches(double meters, unsigned int *ftPtr, double *inPtr) {
    double feet;
    double inches;

    double rawFeet = meters * 3.281;

    inches = modf(rawFeet, &feet);

    if (ftPtr) {
        *ftPtr = feet;
    }

    if (inPtr) {
        *inPtr = inches;
    }
}

int main(int argc, const char * argv[])
{
    double meters = 1.80;
    unsigned int feet;
    double inches;

    metersToFeetAndInches(meters, &feet, &inches);
    printf("%.2f meters is %d feet and %.2f", meters, feet, inches);
    return 0;
}

Upvotes: 0

Views: 382

Answers (3)

Fekete Ferenc
Fekete Ferenc

Reputation: 119

You can store a double in an unsigned int, but the sizes are not the same. While sizeof(unsigned int) is 4 in a 32 bit system, sizeof(double) is 8. So you can store a 8 byte long value in a 4 bytes long space, but loss of data can happen (the upper 4 bites can be trimmed of the original double value).

Upvotes: 0

brokenfoot
brokenfoot

Reputation: 11649

Pointer is just an address:

A char pointer can point to a block of data, which can be anything (int, char, long, double). But when you print it, you'll see only the data that can be contained in that data type. i.e. in this case if char pointer points to int, then only the 1st byte of the int will be printed. No harm done.

But it will be improper, not what you'd expect.

Upvotes: 1

Yes, this is fine.

The double will first be converted to an unsigned int, and then it will be stored. It's as if you had written:

if (ftPtr) {
    *ftPtr = (unsigned int)feet;
}

Upvotes: 4

Related Questions