-1

I'm interested in What is the difference between (int)a and *(int*)&a. They have different outputs.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Note this site uses markdown. If you delimit code with backticks ("`"), it will be formatted as code. Otherwise, certain characters (such as asterisks) are interpreted as formatting. Read the formatting help (accessible when posting and the help center) for more. – outis Jan 30 '21 at 10:19
  • 4
    What's the *type* of `a`? Can you post [mcve]? – P.P Jan 30 '21 at 10:23
  • the type of 'a' is a float – user15111237 Jan 30 '21 at 10:27
  • 1
    In addition to complete code, sample input and output/results (if any) should be included, including both expected/desired results and actual (if the two are different). Clarifications should be edited into the question. – outis Jan 30 '21 at 10:28
  • Casting a `float*` to `int*` and reading as if it's an `int` object isn't allowed - `*(int*)&a` is undefined behaviour. – P.P Jan 30 '21 at 10:29
  • 2
    Does this answer your question? "[Dereferencing the address of a pointer-casted variable](https://stackoverflow.com/q/56074903/90527)", "[What does i = * ( long * ) &y; do?](https://stackoverflow.com/q/47946741/90527)", "[Why cast to a pointer then dereference?](https://stackoverflow.com/q/39312058/90527)" – outis Jan 30 '21 at 10:32

1 Answers1

0

There is a big difference between the two expressions.

In this expression

(int)a

the value of the object a is converted to an integer value of the type int.

In this expression

*(int*)&a

the sub-expression (int*)&a says the compiler that there is allocated memory for an object of the type int that is that in the memory there is indeed stored a valid object of the type int. However the initial memory extent allocated for the object can be larger than an extent that stores a valid object of the type int or there can be stored not an object of the type int and as a result dereferencing the pointer can result in undefined behavior.

That is using the first expression the compiler tries to convert a value to a value of the type int while in the second case the compiler tries to interpret an extent of memory as it stores a valid object of the type int.

Here is a demonstrative program.

#include <stdio.h>

int main(void) 
{
    double x = 1.5;
    
    printf( "%d\n", ( int )x );
    printf( "%d\n", *( int *)&x );

    return 0;
}

Its output is

1
0

And another example when using an expression like this *(int*)&a can produce a valid code and result.

#include <stdio.h>

int main(void) 
{
    struct A
    {
        int x;
        int y;
    } a = { .x = 10, .y = 20 };
    
    printf( "%d\n", *( int *)&a );

    return 0;
}

The program output is

10
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335