+15

Return type in C

for example a function return type is int but can still output floats. Considering this code. Does it mean the return type doesnt affects outputs of the code? Can someone please shed some lights. int sum (int, int); int main(){ int x = 5; int y = 10; float result =sum(x + y); Printf("%d + %d = %.2f", x,y, result); } int sum(int x, int y){ return x + y; }

9/18/2019 1:49:56 AM

BlackRose Mike

6 Answers

New Answer

+10

Fuzzy Squid Then how do we use it or make it do something as you said

+10

Maninder $ingh i see, i was expecting it to throw an error or a warning but it didnt.

+4

BlackRose Mike this is your answer man. Actually if you look deep in your code.your function sum actually return a int value,but in main function you are storing your int value returning from function in result variable which is float type that's why result variable converting your int value to float value. But actually sum function always returning int value.

+4

BlackRose Mike try this code actually your code have many errors. int sum(int x, int y){ return x + y; } int main(){ int x = 5; int y = 10; float result = sum(x,y); printf("%d + %d = %.2f", x,y, result); }

+2

Return doesn't do anything unless you want it to do something. The function Sum returns x + y as a return value, and it stores that value, but doesn't do anything with it. You can use printf() to get the value of x + y, or use it in some other way, but unless you use it, it won't do anything...

+2

You could print out the return value is you print out the function, so it would look something like this: variable = Sum() Printf(variable); You could also use it with comparisons and if statements... if(a>b) return a; else return b; For more info: https://www.sololearn.com/Discuss/1959846/how-to-use-the-return-function https://docs.microsoft.com/en-us/cpp/c-language/return-statement-c?view=vs-2019 BTW, not really into C, so sorry if the syntax is a little off...