Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code Implementation defined?

Tags:

c

pointers

#include<stdio.h>

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

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

Will the output of the above code implementation defined and the output will vary between little endian and big endian machine?

like image 489
fuzzy Avatar asked Sep 12 '12 04:09

fuzzy


People also ask

What is the meaning of implementation defined?

Implementation is the execution or practice of a plan, a method or any design, idea, model, specification, standard or policy for doing something. As such, implementation is the action that must follow any preliminary thinking for something to actually happen.

What is the difference between unspecified and undefined?

Undefined Behavior results in unpredicted behavior of the entire program. But in unspecified behavior, the program makes choice at a particular junction and continue as usual like originally function executes.

What is implementation defined Behaviour in C?

Implementation-defined behavior is defined by the ISO C Standard in section 3.4.1 as: unspecified behavior where each implementation documents how the choice is made. EXAMPLE An example of implementation-defined behavior is the propagation of the high-order bit when a signed integer is shifted right.

What is well defined behavior?

A behavior that is appropriately defined should be clear and concise. It should be observable and measurable. Multiple people should be able to observe and measure the same thing. Try to make your definition as specific as you can. This allows you to help the learner make progress more easily.


2 Answers

Yes. The classic way to detect endianness at run time is the following way:

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

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

Even though 257 => 0x0101, an int is most likely 32 bits in which case on a BE machine it will print 00 and on LE, 11.

like image 98
James Avatar answered Sep 30 '22 02:09

James


Yes it will. I always write it this way since I am never sure about operator precedence:

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

And to achieve what you want change your %d to a %c in the format string.

like image 42
Mario The Spoon Avatar answered Sep 30 '22 04:09

Mario The Spoon