-5

I am trying to workout the output of the below given c program but unable to figure out.

Why is si = 0?

#include<stdio.h>

int main(void){

    float p = 1000;
    float r = 5;
    float t = 2;

    float si = p * r * t / 100;

    printf("SI = %d", si);

    return 0;

}

1 Answers1

2

You are passing value in floating point representation while you used %d specifier which forces printf to expect an int.

There is no 'automatic cast' when you pass variables to a variandic function like printf, the values are passed into the function as the datatype they actually are (or upgraded to a larger compatible type in some cases) because is weakly typed language.

If you pass type with incompatible internal representation you will get garbage output.

Change

printf("SI = %d", si);

to

printf("SI = %f", si);

or (if you would like to get integral value of expression)

printf("SI = %d", (int)si);
kocica
  • 6,412
  • 2
  • 14
  • 35
  • any idea why is he getting 0 instead of expected garbage value? – Vikas Yadav Aug 29 '17 at 18:28
  • 1
    @VikasYadav Consider: I send you a `float` and put it in the `float` box. You look in the `int` box and see ... nothing .... and print that. Perhaps a 0 left over from before, maybe not, maybe the boxes overlap? It is _undefined behavior_. – chux - Reinstate Monica Aug 29 '17 at 18:57