0

Can somebody explain the output of the following program:

int main()
{
    int i=512;
    char *c=(char*)&i;
    c[0]=1;
    cout<<"i is:"<<i<<endl;

    return 0;
}

output is:513

jrok
  • 54,456
  • 9
  • 109
  • 141

3 Answers3

3

The output of your program unspecified. In practice, it depends on the endianness of your platform and the width of the int type.

Your platform is little-endian. Let's for simplicity assume that int is 32 bits wide.

51210 is 0x00000200 in hex. This is stored in memory as

00 02 00 00

Your code modifies the first byte to 01. This changes the int to 0x00000201, which is 513 decimal.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 2
    This is implementation specific value. Aliasing with `char` is explicit exception to strict aliasing. – Maciej Piechotka Oct 30 '13 at 10:58
  • Why is it undefined behavior? As long as the endianess is known, I don't see why it should be not well-defined what's happening. Can you explain why it is UB then? – leemes Oct 30 '13 at 10:58
  • I've reworded the answer. I believe it is correct now. Let me know if you think otherwise. – NPE Oct 30 '13 at 11:02
  • Well, if it *really* is UB then the previous version was correct. I don't know if it is UB, I only wanted to know why you thought it would be. – leemes Oct 30 '13 at 11:05
  • 3
    @leemes *As long as the endianess is known.* Where in the standard is endianness mentioned? – David Heffernan Oct 30 '13 at 11:17
2

The program exhibits unspecified behaviour, dependent on the architecture of the machine. To predict and reason about the output requires knowledge of the compiler and the target architecture.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
2

Explanation:

int main()
{
    /* Creates int equal to 512 */
    int i=512;

    /* Creates a char pointer, and points this at i */
    char *c=(char*)&i;

    /* Overwrites the lowest byte of the 4 byte int with 1 */
    /* This sets the lowest bit of the int, which adds 1 */
    c[0]=1;

    /* Displays the updated int */
    cout<<"i is:"<<i<<endl;

    return 0;
}

Exactly which part of the int gets overwritten depends on the endianness of the platform you're compiling for. Given the final result of 513, your system is clearly little-endian.

Baldrick
  • 11,712
  • 2
  • 31
  • 35
  • You should probably qualify your explanation as applying specifically to little endian architectures. – Paul R Oct 31 '13 at 07:05