undefined behavior - Explanation of output of C code -
undefined behavior - Explanation of output of C code -
i came across code:
#include<stdio.h> void main() { int x; float t; scanf("%f",&t); printf("%d\n",t); x=90; printf("%f\n",x); { x=1; printf("%f\n",x); { x=30; printf("%f\n",x); } printf("%f\n",x); } printf("%f\n",x); } glancing @ thought of undefined output quoted in standards:
a warning: printf uses first argument decide how many arguments follow , type is. confused, , wrong answers, if there not plenty arguments of if wrong type.
but output didn't allow me leave question without giving sec thought. (input given 23).
23 0 23.000000 23.000000 23.000000 23.000000 23.000000 why 23.00000? compiler trying here? instead of messing around value stored @ x, why print value of t? have explanation, because there seems defined undefined output (pun intended).
i using gcc compiler on 32 bit machine.
the programme behavior undefined, compiler permitted @ all.
that said, able reproduce behavior on scheme , glance @ assembly output shows happens:
printf("%d\n",t); begins loading floating point value t cpu register %xmm0 used on platform pass floating-point arguments functions. register not accessed phone call printf(), since looking integer input instead.
none of subsequent calls printf() load values %xmm0, since you're not passing floating-point values printf or other function. when each printf encounters %f in format string, reads %xmm0, still contains 23.0
assembly output, clang, using simpler programme float t = 23.0;
.lcpi0_0: .quad 4627167142146473984 # double 2.300000e+01 ... movl $.l.str, %edi # .l.str "%d\n" movsd .lcpi0_0(%rip), %xmm0 # 23.0 stored in xmm0 here movb $1, %al callq printf # printf print %esi movl $90, %esi # 90 stored in %esi here movl $.l.str1, %edi # .l.str1 "%f\n" xorb %al, %al callq printf # printf print %xmm0 c undefined-behavior
Comments
Post a Comment