Honesty Rocks! truth rules.

Kinda Noobie Questions On C++ Functions and stuff

HOME      >>       Programming


I have a few questions on C++ mainly about functions.

Why does int main() have to return a value?

Why are parameters/arguments used in int main()?

In the following program, doesn't all of the code need to be executed into the int main() part?

#include <iostream>using namespace std; void box(int length, int width, int height) int main(){ box(7, 20, 4); box(5, 4, 3); box(24, 1, 5); return 0;} void box(int length, int width, int height){ cout << "The volume of box is: " << length * width * height << "\n"; }

Thanks in advance~!!


This is the programming power that you use there is nothing deep sense just use the programming skill and use logic to complete our taske any how any cost search the required logic and programmed it.in your case C++ compiler facility it must return integer value so thats by here int return.


I'm not quite sure what you mean by this. Are you asking why not all the code is in the main function? The code that is outside the main function is the declaration of the function named "box". It is essentially the same as the main function, except it doesn't return anything, and it is not called by the computer when the program is run. When you run your program the computer calls the main function which runs whatever is inside. If nothing calls the box function it will never run, however in the example code you have provided, the main function calls the box function. In fact it calls it three times. Perhaps the question you should be asking first is "What is a function?"

I meant, I was told that ALL of the code should be executed in the main() function. Well, I don't understand why can't the void box() function be IN the int main() function. Can there only be one function executing at the same time?

I am so confused....


It can all be in main, but it is split to make it easier to read.The reason is that when you get longer programs, it's easier to break it into smaller blocks...Think of it like this...On one hand you could organize your list of continents and countries like this..1 - USA2 - Brazil3 - Australia4 - Canada5 - AfricaOr you could organize it like this..1)North America A) USA B)Canada2)South America A)AfricaAnd so on. The second list is easier to read because it's much more organized. The same goes with programs. As you go on you will write longer and longer programs, some going 30k+ lines. This helps to cut down on the hassle of going through one line at a time looking for what went wrong.In the beginning, though, I would just put everything in Main.Hopefully that helps you understand it better.


I see. But what dies the main() function actually do if it is not where all the code is executed?


Oh, so main() is what the compiler runs first then it runs the other functions next in order....


Oh ok, thanks~!! =)