August Karlstrom
August Karlstrom

Reputation: 11377

What is the correct way to type-cast a number?

Is the following program well defined or can it cause undefined behavior?

#include <assert.h>
#include <stdio.h>

int main(void)
{
    float x, y;
    int i;

    assert(sizeof (x) == sizeof (i));
    x = 3.14;
    i = *(int *) &x;
    y = *(float *) &i;
    printf("%f %f\n", x, y);
    return 0;
}

If it can cause undefined behavior, is there another way to change the type of a floating point value to an integer type without changing the bit pattern of the value?

Edit:

What I'm trying to implement is a macro similar to

#define CONV(T, n) ((T) (n))

but which doesn't alter the bit pattern of n.

Upvotes: 0

Views: 52

Answers (1)

Paul Hankin
Paul Hankin

Reputation: 58271

Yes, it's undefined behavior to access float data through an int* pointer (it violates strict aliasing).

The standard way to do type punning is to write memcpy(&i, &x, sizeof(i)) instead of i = *(int*)&x.

This is a good resource: What is Strict Aliasing and Why Do We Care

Upvotes: 3

Related Questions