How a different data type variable inside a printf statement affects each other relatively in print order

When I executed this piece of code:

void main(){
    float a=3;
    int b=5;
    printf( "%d %d \n", a, b);
}

I got a conclusion like

0 1074266112 

and when I changed the print order, i.e.

printf("%d %d \n",b,a);

I got this as output:

5 0

Why?

+4
source share
6 answers

Since your qualifiers do not match the actual values, you invoke undefined behavior. This means that anything can happen, and especially the behavior can change between program calls (if format specifiers read more data than is actually provided) or at least between compiler settings.


, , , int . , .

: float double , 8 .

:

#include <stdio.h>

void main(){
    float a=3;
    int b=5;
    printf("%08x %08x %08x\n", a, b);
    printf("%08x %08x %08x\n", b, a);
    printf("%d %d %d\n", a, b);
    printf("%d %d %d\n", b, a);
}

00000000 40080000 00000005
00000005 00000000 40080000
0 1074266112 5
5 0 1074266112

, . printf(). - ( %08x),

00 00 00 00  00 00 08 40  05 00 00 00
05 00 00 00  00 00 00 00  00 00 08 40

,

00 00 00 00 -> 00000000 -> 0
00 00 08 40 -> 40080000 -> 1074266112
05 00 00 00 -> 00000005 -> 5

.

%d, ,

0 1074266112
5 0

.

, , b , , "" a.

+3

undefined; - .

.

, float , . printf %f %lf. , .

:

float a=3;
int b=5;
printf( "%d %d \n", a, b);

( int 4 )

float, double 8 , , 4 . 8 (% d 4 ), 4 4 () double. .

:

printf( "%d %d \n", a, b);

, , , 4 .

+3

, printf , , printf , . scanf.

undefined. , %d float a.

float a = 3;
int b = 5;

// undefined behaviour due to %d for a
printf( "%d %d \n", a, b); 

Undefined , . , . , , . , , -

+2

.

  • 32- , "%d %d", printf 4 int, 4 int.
  • float printf, double, , 8 .

.

, printf( "%d %d \n", a, b);, 12 , 8 float a 4 int b. %d %d, printf 4 a 0. 4 a 1074266112.

, printf("%d %d \n",b,a);, 12 , 4 b, 8 a. , printf b , 4 a 0.

+2

% d .

printf ( "floats: %4.2f %+.0e %E \n" , 3.1416, 3.1416, 3.1416); 
0

When the argument is cast to an integer, the value is not delivered using the floating point library or the calculation function. Therefore, it becomes different from the assumption. For example, if in the case where the program you showed is launched by the x86 architecture, only the value with which the command was executed by the mmx command will be displayed. If the existence of this operation uses gcc, it is useful to specify the -S option.

0
source

Source: https://habr.com/ru/post/1537062/


All Articles