Course Content
C++ Introduction
C++ Introduction
Type of Functions
When creating a function, the data type it returns always specified.
In the example of the main function, we see that it has an integer data type, which means that after it finishes its work, it will return an integer value, in our case, the number 0.
Note
Since the
main
function is reserved in C++, it will always return integer.
But our functions can return any value:
To call a function, you need to write its name with brackets:
main
#include <iostream> double notMainFunc() { return 3.14; } int main() { std::cout << notMainFunc(); }
We have created a function that returns a value of 3.14
as a double
data type, and we have called this function to display its output on the screen.
Functions can also be string
type:
main
#include <iostream> #include <string> std::string notMainFunc() //string function { return "codefinity"; } int main() { std::cout << notMainFunc(); //calling string function }
The typedef
is also applicable:
main
#include <iostream> typedef int MY_NEW_TYPE; MY_NEW_TYPE TYPEfunc() //MY_NEW_TYPE function { return 777; } int main() { std::cout << "New type func returned " << TYPEfunc() << std::endl; }
If you can't exactly specify the return type, the auto
operator will force the compiler to do it for you:
main
#include <iostream> auto autoFunc1() // first auto-type function { return 777; } auto autoFunc2() // second auto-type function { return 123.412; } int main() { std::cout << "First auto-type function returned " << autoFunc1() << std::endl; std::cout << "Second auto-type function returned " << autoFunc2() << std::endl; }
Thanks for your feedback!