3

I have been working on this quiz: https://www.sanfoundry.com/c-quiz-pointers-addresses/

and don´t understand why casting an int to a float would output 0.000000

    #include <stdio.h>
    int main()
    {
            int i = 10;
            void *p = &i;
            printf("%f\n", *(float*)p);
            return 0;
    }

Expected output: 10.000000

Actual output: 0.000000

Thank you very much for your help!

alk
  • 69,737
  • 10
  • 105
  • 255
clearner
  • 81
  • 3
  • "*casting an int to a float*" you are not doing that. You are casting the *address* (`p`) of an `int` to the *address* of a `float`. This is something completely different. – alk Jan 25 '19 at 12:25
  • 1
    violation of strict aliasing results in undefined behaviour, in which any result can happen – izac89 Jan 25 '19 at 12:25
  • 1
    Note that answer given on quiz is incorrect. – user694733 Jan 25 '19 at 12:26
  • 1
    It's indeed bewildering: The correct answer is even listed (b) but the incorrect one is given as solution (d) with no explanation.. – Ctx Jan 25 '19 at 12:55

1 Answers1

4

You're not casting an int to a float.

You're attempting to cast an int* to a float*.

The language does not allow you to do that and as such the behaviour of your code is undefined. The rationale is to afford maximum flexibility for architectures supporting C: they might put float data in a different memory location to int data.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • can you give more information or examples of systems that `put float data in a different memory location to int data` ? – izac89 Jan 25 '19 at 12:30
  • @user2162550: From memory some of the Intel 286 machines with a separate math co-processor (early 1990s) used to do this. – Bathsheba Jan 25 '19 at 12:31
  • 1
    @Bathsheba The "different memory location" can be relevant when the format specifier for `printf()` mismatches (printf looks in the wrong location then), but not in the given case. – Ctx Jan 25 '19 at 12:52
  • 1
    @user2162550 Imagine a system where `float` values have to be aligned on a multiple of four bytes, but an `int` has less restrictive alignment requirements, like a multiple of two bytes or any address at all. On such a system, the posted code would fail if the `int i` were not aligned properly for a `float`. For many, many, many examples, just Google [`SIGBUS` SPARC](https://www.google.com/search?q=sigbus+sparc). – Andrew Henle Jan 25 '19 at 13:46