Is this code implementation defined?

#include<stdio.h>

int main (void)
{
  int i=257;
  int *ptr=&i;

  printf("%d%d",*((char*)ptr),*((char*)ptr+1));
  return 0;
}

Will there be a result of the implementation of the above implementation of the code, and the output will be different from the small final and large finite machines?

+5
source share
3 answers

Yes, this will be a specific implementation behavior.

When you click ptron (char *)and then access the first memory cell, the first byte stored in the memory will be available, which will depend on whether the system is a large or a low-value system.

Before calling the function, the printfarguments are evaluated. And this assessment, as mentioned above, will receive different values ​​for different systems. Therefore, this implementation is defined.

+2
source

. - :

uint32_t var = 1;
uint8_t *ptr = (uint8_t*)&var;

if(*ptr) puts("Little Endian");
else puts("Big Endian");

, 257 = > 0x0101, int, , 32 , BE 00 LE, 11.

+8

Yes it will. I always write it like this, since I’m never sure of the priority of the operator:

*(((char*)ptr)+1)

And to achieve what you want, change your %dto %cin the format string.

+3
source

All Articles