Garbage value when passed float values to the function accepting integer parameters

后端 未结 1 598
情话喂你
情话喂你 2020-12-20 09:07
#include
int main(){
 int ret = 0;
 ret = func(1.0,2.0);
 printf(\"\\n ret : %d \\n\",ret);
 return 0;
}
func(int a,int b){
 float m = 5.0;
 float n =         


        
相关标签:
1条回答
  • 2020-12-20 09:37

    You need to provide a declaration for func before calling it

    int func(int a,int b);
    int main() {
    }
    int func(int a,int b) {
        // implementation
    }
    

    Your code presumably compiled with a warning something like warning: implicit declaration of function 'func'. If you'd fixed this warning, you'd also have fixed the error.

    It'd be good practice to have the compiler warn you about as many potential problems as possible. You may also want to guard against the possibility of missing warnings by treating them as errors. You can do this by adding -Wall -Werror to your build command for gcc or /W4 /Wx for MSVC.

    Note that the correct value is returned if you pass ints into func. At a guess, this may be because the calling code doesn't know that it needs to cast the arguments to int and passes float instead. func then either reads registers/stack locations that floats weren't copied to or receives the bit representations of float arguments and treats them as int. Either of these will result in incorrect values of a, b being received. You can check this yourself by adding a printf inside func to note the values of its arguments.

    0 讨论(0)
提交回复
热议问题