Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected result in C program

Tags:

c

Can you please explain the output of this C program? I guess that the problem is with the stack getting corrupt during printf("%d\n",t); function call because I'm pushing a float but reading an int. I'm not sure.

#include <stdio.h>

int main() 
{ 
    long x; 
    float t; 
    scanf("%f",&t); 
    printf("%d\n",t); 
    x=30;
    printf("%f\n",x); 
    { 
        x=9;
        printf("%f\n",x); 
        { 
            x=10;
            printf("%f\n",x); 
        } 
        printf("%f\n",x); 
    } 
    x==9;
    printf("%f\n",x); 

}

And the output

$ ./a.out 
20.39
0
20.389999
20.389999
20.389999
20.389999
20.389999
$
like image 540
svpranay Avatar asked Mar 23 '11 09:03

svpranay


2 Answers

What happens is that you lie to the compiler ... first you tell it you are going to send an int to printf but you send a float instead, and then you tell it you are going to send a double but you send a long instead.

Don't do that. Don't lie to the compiler.

You have invoked Undefined Behaviour. Anything can happen. Your program might corrupt the stack; it might output what you expect; it might make lemon juice come out of the USB port; it might make demons fly out of your nose; ...

like image 100
pmg Avatar answered Oct 23 '22 22:10

pmg


You are using the wrong format specifier to print long. Use format specifier %ld instead. Results

printf("%f\n",x);
     // ^ change this to %ld 
like image 41
Mahesh Avatar answered Oct 23 '22 22:10

Mahesh