Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

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

#include<stdio.h>
int main(){
 int ret = 0;
 ret = func(1.0,2.0);
 printf("
 ret : %d 
",ret);
 return 0;
}
func(int a,int b){
 float m = 5.0;
 float n = 6.0;
 int sum = m + n;
 printf("
 sum : %d 
",sum);
 return a+b;
}

EDITED

sum : 11

ret : -877505847

why the float value passed to the integer throws a garbage value while the float value added and assigned to an integer inside the function gives the correct value 11 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...