-3

Intro
Hello! I recently started learning C++. I stopped learning python, because it didn't interest me that much as C++. I am a completely beginner in C++.

Context
My question is that do I need to make a main function for every thing I do?
For example, to print something

#include <iostream>

int main()
{
    std::cout <<"Hello World!;
}

So I made it print "Hello World!".
Let's say for something similar do I need to make a new int main()? Or is everything going to be contained inside main()?

Sorry if I made this complicated, every answer is appreciated!

Kitswas
  • 1,134
  • 1
  • 13
  • 30
  • 6
    It appears you could benefit from a [good C++ book](https://stackoverflow.com/a/388282/4641116). – Eljay Jul 16 '21 at 12:08
  • 2
    I'm not really sure what you are asking. `main` is the entry point of your program. Every C++ program needs one and only one `main`-function. That's the first function of your code that's being called from outside. – Lukas-T Jul 16 '21 at 12:11
  • If you want to print two things, you can just put another `std::cout` statement in `main`. It isn't clear why you expect to need multiple `main`, but an executable will have exactly 1 `main` which indicates where the program starts. It can't start in multiple places. – François Andrieux Jul 16 '21 at 12:44
  • Good choice of languages, however, neither is learned by guesswork. The link in the comments above provides a good selection of resources to help you learn properly. – David C. Rankin Jul 17 '21 at 06:24

3 Answers3

0

You don't need another main() function.

int main() is the entry point to your program. It is called immediately after initialization of any statically allocated variables.

You should write another function, let's name it add(), and call it from within main(). This lets you split your code up into smaller chunks that are more easily writeable, readable and maintainable.

For example: We want a program that will print "Hello World!" to the console, then call another function that could print something else.

#include iostream

int main() {
    std::cout << "Hello World" << endl; //endl designates the end of a line
    printSomethingElse();
}
0

do i need to make a main function for every thing I do?

No, you do not need to have a main() for everything you do. You just need to have a main() to run your source code.

The main() function is your entry-point into your program in C++; unlike Python which is executed (or run/interpreted) top-down.

Priyanshul Govil
  • 518
  • 5
  • 20
-1

For modules like console applications, applications using windows or widgets, dynamic link libraries (Windows) or shared libraries (Linux), you need exactly one main-function. But not for static libraries. Static libraries are linked statically and don't need a main function. They are just collections of functions without a main entry point.

Regards

Martin.Martinsson
  • 1,894
  • 21
  • 25