Buddy Pall
Buddy Pall

Reputation: 21

Cannot print called float variables

I cannot print float variables when calling my functions. int variables print but floats won't print their proper value when passed to my function.

I tried to change the float to int and that worked

int main() {
    int foo = 6;
    call(foo);
}

void call(int bar) {
    printf("%d", bar);
}

This worked and it does indeed print 6.

But, doing the same but with floats only prints out 0.00000:

int main() {
    float foo = 6;
    call(foo);
}

void call(float bar) {
    printf("%f", bar);
}

How do I correctly call and then print float variables?

Upvotes: 1

Views: 89

Answers (3)

Ted Lyngmo
Ted Lyngmo

Reputation: 117831

You could simply define call above main instead of below it. The compiler must have seen the declaration of functions when they are used, so a forward declaration like pm100 suggests is one way. Moving the whole definition above main is the another (that does not require a forward declaration).

#include <stdio.h>

void call(float integerrrr){
    printf("%f", integerrrr);
}

int main(void){
    float integerrrr = 6;
    call(integerrrr);        // now the compiler knows about this function
}

INT type variables i can print but float just does not

If your program actually compiles as-is it will use an old (obsolete) rule that makes an implicit declaration of undeclared functions when they are used. The implicit declaration would be int call(); - which does not match your actual function. The program (even the one that seems to be working) therefore had undefined behavior.

Upvotes: 2

bilel abdelmoula
bilel abdelmoula

Reputation: 37

the compiler of c work from top to bottom so line by line, so u will have to call the first function void call() then your main function:

void call(float integerrrr){
printf("%f", integerrrr);

}

int main(){
  float integerrrr=6;
  call(integerrrr);
}

Upvotes: 1

pm100
pm100

Reputation: 50210

you need a forward declaration of call

void call(float integerrrr);

int main(){
  float integerrrr=6;
  call(integerrrr);
}

void call(float integerrrr){
  printf("%f", integerrrr);
}

your compiler probably warned you about this

Upvotes: 3

Related Questions