0
Confused about difference between Void and Int functions?
I created a little explanation about this topic and I want to share with you all. I hope it helps you to clarify things better
3 Antworten
+ 6
int returns an integer. void doesn't return anything.
+ 2
This is the explanation every coding teacher always gave me. To me, the word "return" may have lots of meanings. In some points of view, a printing method is returning information to the user through the screen, so, it can be interpreted as a "return" by a beginner. This kind of explanation had no use to me when I started coding. I understood thanks to practical examples and exercising
+ 1
I know how you feel. Some months ago, I was on your shoes. The main difference is noticed if you try to create 2 mathematic functions to do the same thing.
Let's create a function to sum 2 integers:
int sum(int a, int b)
{
return a + b;
/*the return keyword must always be in "non void" functions. Perhaps, it only returns single values, without any kind of text*/
}
void sum(int a, int b)
{
int result;
result = a + b;
printf("%d\n", result );
/*in this case, as we declared the function as void, it has no numerical or logical return. If you want something to be shown, you must print it inside the scope of the function. You can print texts too, as we're dealing with double quotation marked strings when we're printing results*/
}
Another advantage is that you can define what's gonna be printed inside the scope instead of printing things outside of the function. It means that, in void functions, you can define texts to be printed everytime the function is gonna be called.
example 1:
int sum(int a, int b)
{
return a + b;
}
int main(){
int num1 = 2;
int num2 = 4;
printf("Sum of the 2 numbers is %d", sum(num1,num2));
return 0;
}
example 2:
void sum(int a, int b)
{
int result;
result = a + b;
printf("Sum of the 2 numbers is %d", result);
}
int main(){
int num1 = 2;
int num2 = 4;
sum(num1, num2);
return 0;
}
I hope it helps you to clarify things