Different performance every time in c?

I am trying to learn C and I am very confused.

#include <stdio.h>

int main(void)
{
    int a = 50000;
    float b = 'a';
    printf("b = %f\n", 'a');
    printf("a = %f\n", a);
    return 0;
}

The code above produces a different output each time with gcc. Why?

+4
source share
6 answers

You pass a value int('a') for a format %fthat expects floator double. This behavior is undefined, which can lead to different results for each execution of the same program. The second printfhas the same problem: %fexpects floator double, but you pass the value int.

Here is the corrected version:

#include <stdio.h>

int main(void) {
    int a = 50000;
    float b = 'a';

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

    return 0;
}

Conclusion:

a = 50000
b = 97.000000
'a' = 97

, -Wall -W -Wextra . .

, clang :

clang -O2 -std=c11 -Weverything fmt.c -o fmt
fmt.c:8:24: warning: implicit conversion increases floating-point precision: 'float' to 'double' [-Wdouble-promotion]
    printf("b = %f\n", b);
    ~~~~~~             ^
1 warning generated.

b double printf(). double , float, , , .

double float , , API- , ...

+2

%f (float double), int. undefined, , .

, , :)

: chqrlie !

+1

.

. %f char int undefined.

yo:

printf("%d\n", 'a'); // print ASCII value
printf("%d\n", a);
+1

, ( %f) ( ... printf) ( , 'a', , int) .

ABI. , x86_64, %xmm0 printf ( ), gcc %rdi printf.

. Application Binary Interface AMD64 Architecture Processor Supplement, p. 56

, C - , ( , , ) . ( ), , .

+1

, gcc . .

(printf(), scanf()) C. , gcc, , , int - float.

.
fooobar.com/questions/1286915/...
fooobar.com/questions/1439035/...

expetced.

#include <stdio.h>

int main(void)
{
    int a = 50000;
    float b = 'a';
    printf("b = %f\n", (float)'a');
    printf("a = %f\n", (float)a);
    return 0;
}
0

The main difficult point that you have is the type of data you are using. When you create a variable, you specify the size that the memory must reserve for proper operation. For example, charthey have a size of 1 byte intequal to 4 bytes and float32 bytes. It is important to use the same data type so as not to have unpredictable results.

char a = 'a';
printf("%c",a);

int b = 50000;
printf("%d",b);

float c = 5.7;
printf("%f", c);

For more information: C-Variables

0
source

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


All Articles