Return types | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Return types

They say return type specifies the type of a value that the function returns but why in the main function we use int although that we get all types of values when we execute anything inside it And when it comes to void they say no value is returned can I know what this means?? Could u guys explain to me??

31st Jul 2019, 7:08 PM
Majd Alkwaja
Majd Alkwaja - avatar
5 Answers
+ 4
We use int in main function because we return 0 from it. Returning 0 from main function indicates that the program execution was successfull. If we we return - 1 it means there is some error/problem and program execution was unsuccessful. You can skip the return statement in the main function, compiler will automatically add return 0 in the end upon successful execution else -1.
31st Jul 2019, 7:18 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 3
No you can't put any other data type other than int. Its because 'int main()' is a signature of C/C++ main function. If you look another way around, the compiler has to return either 0 or -1 which are integers. So let's say you write char main() and in the end you/compiler is returning an integer value so it will definitely give an error. Sidenote: You could use void main but it won't work now. It could be used in old compilers like Turbo-C but in modern compilers you need to use int main.
31st Jul 2019, 7:29 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 2
thanks mate❤️
31st Jul 2019, 7:12 PM
Majd Alkwaja
Majd Alkwaja - avatar
+ 2
When you declare a method you need to decide whether this method is going to return somthing back or not. If not then we use "void" this means that your method will do somthing when called like change the value of a field or print somthing to console but nothing is actully returned to were you called that method in main. If you want somthing returned back to were you called that method then you need to give your method a return type which could be a string,int ect... This is the same in c++ the method called is main which returns a int value to say whether the method ran successfully or not, anything else that happends in the method is irrelevant as long as it works.
1st Aug 2019, 7:50 AM
D_Stark
D_Stark - avatar
0
so can i for example put char and put a character in return in the main function. or it does not work
31st Jul 2019, 7:22 PM
Majd Alkwaja
Majd Alkwaja - avatar