0

Can anyone elaborate why do we use return 0 and void?

I am always confused with the sentence that void is used when function does not return anything. Can anyone elaborate my question and what does function return in certain cases, etc?

26th May 2019, 8:19 AM
Yash Thakkar
Yash Thakkar - avatar
2 Réponses
+ 3
A function is defined like this: <return_type> function_name([<parameter_type> parameter_1] [, <parameter_type> parameter_2, (...)]); Example: int sum(int a, int b) { return a + b; } Here, the first "int" is the return type, "sum" is the name of the function and "int a" and "int b" in parentheses are the parameters that the function expects. This function returns the sum of the parameters (a + b) which is also an integer. ~~~ int string_length(char *string) { return strlen(string); } This function takes a pointer to char (char*) as a parameter and returns the length of the string which is an integer. It would be called like this: string_length("Hello"); // return value: 5 (an integer) ~~~ If a function does not return anything, use the keyword "void". void say_hello() { puts("hello"); } This function doesn't take any parameters (hence the empty parentheses) and doesn't return anything, that's why its return type is "void" and there is no "return" statement in the function. ~~~ Even in a void function, you can still use the "return" keyword to exit the function: void myfunc() { int i = 0; while(true) { // infinite loop ++i; // count from 0 to infinity if(i > 40) { return; // exit function } } } This function isn't meant to return anything. Once i gets larger than 40, the function will be exited because of the return statement.
26th May 2019, 8:45 AM
Anna
Anna - avatar