So this seems to be a frequently asked question but on more complex problems. I am just starting out and am coming from a higher level language (python) and thus a bit confused as to what C++ wishes me to specify. I have 2 virtually identical functions and when I run the file it seems to just output one of them and I am not sure why not both. It seems to be something with the naming. C++ seems to want to prefer things named as main().
I feel for someone with experience this may be quite obvious and I would be thrilled to also have some more details about the goings on of C++ and how/why it determines what functions to "prefer". (I am using a VScode environment)
#include <iostream>
using namespace std;
int starter()
{
//declaring variables
int a, b;
int result;
// process
a = 5;
b = 2;
a = a + 1;
result = a - b;
//print the result
cout << result;
//terminate the program
return 0;
}
int main()
{
int a = 5; //"c-like"
int b (3); // "constructor"
int c {1}; // "uniform"
int result; //initial value undetermined
result = a + b - c;
cout << result;
return 0;
}
Only the main(){} block of code is executed
>Solution :
From the C++23 draft [basic.start.main]:
6.9.3.1
- A program shall contain exactly one function called
mainthat belongs to the global scope. Executing a program starts a main thread of execution ([intro.multithread],[thread.threads]) in which themainfunction is invoked.
That’s all there is to it. Other functions you wish to be invoked can be called from main either directly or indirectly.
You can also call functions to initialize global variables.
#include <iostream>
int starter()
{
// ...
return 123;
}
int x = starter(); // called before `main`
int main()
{
std::cout << x << '\n'; // prints 123
}