Search code examples
cfunctionprintfpow

function return changed as directly written in printf statement


#include <stdio.h>
#include <math.h>

int main() {
    printf("%d\n", pow(3546, 0));   
    return 0;
}

The above code prints value 0

While the below code prints value 1

#include <stdio.h>
#include <math.h>

int main() {
    int a  = pow(3546, 0);
    printf("%d\n", a);
    return 0;
}

Why is it so? Even though they are equivalent.


Solution

  • There's no equivalence. The latter function explicitly converts the number to int before printing, while the former results in UB by trying to print a floating point number using wrong format specifier -- you're lucky to get 0, you might have gotten an arbitrary number.

    Please, turn on all warnings on your compiler, it should complain about using wrong format for the wrong type of data.