-1

When I run this code the output of D comes out as the value of C. Is it because I call for a float and it just takes the most recent float in the memory?

#include <stdio.h> 

int main()
{
    int a=3/2;
    printf("The value of 3/2 is : %d\n", a );

    float b=3.0/2;
    printf("The value of 3/2 is : %f\n", b );

    float c=7.0/2;                                  <-------
    printf("The value of 3/2 is : %f\n", c );

    int d=3.0/2;
    printf("The value of 3/2 is : %f\n", d );       <-------

    return 0;
}

The value of 3/2 is : 1
The value of 3/2 is : 1.500000
The value of 3/2 is : 3.500000
The value of 3/2 is : 3.500000
Liro
  • 7
  • 3

2 Answers2

2

Arguments that do not match the type indicated by the format specifier yield undefined behaviour (cf., for example, cppreference/printf):

... If any argument is not the type expected by the corresponding conversion specifier, or if there are fewer arguments than required by format, the behavior is undefined.

And undefined behaviour is undefined; it might crash, it might print out nothing, anything, or even something looking correct. Confer, for example, the definition of undefined behaviour in this online c draft standard:

3.4.3 (1) undefined behavior

behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
2

The printf function accesses the amount of memory that matches the format you specify; if you don't provide enough, behavior is undefined and falls between compiler dependent and random.

Probably it reads whatever memory comes after the given address, and because floats are located on different byte boundaries, gets the place where your other variable sits. Another compiler or slight code changes will give something different; it is moot to analyze 'undefined behavior'.

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
Aganju
  • 6,295
  • 1
  • 12
  • 23