Home > database >  int* = int ? Different levels of indirection
int* = int ? Different levels of indirection

Time:12-14

Why does the last line of this segment compile and run in C (Visual Studio)? It is int* on the left and int on the right. The types do not match so I would think it is an error. In other words a data value should not be compatible with a memory address.

    int x = 6;
    int* baz = &x;
    int* foo = &x;


    foo = baz;     /* ok */
    foo = *baz;   /* ?? */

I assumed it would not compile.

CodePudding user response:

MSVC does give a warning for this. You must be ignoring the warning.

Elevate warnings to errors by using the /WX switch.

The C standard requires a diagnostic message for this because it violates the constraint for simple assignment in C 2018 6.5.16 1:

One of the following shall hold:

[list of six cases, none of which covers assigning an int value to a pointer]

However, even a compiler that conforms to the C standard is allowed to accept the program even after issuing a diagnostic for a constraint violation,1 and that is what happened. Using /WX will prevent that.

Footnote

1 It is allowed to do this because there is no rule against it in the standard, and footnote 9 says:

… It [a C implementation] can also successfully translate an invalid program…

CodePudding user response:

You can think of a memory address as an integer. Doing foo = *baz is the same as doing foo = 6.

In other words, your integer pointer foo is now pointing to memory at address 0x6. This still compiles, but if you try to dereference foo, you'll encounter undefined behavior.

  • Related