Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run multiple functions in one file (C++)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

From the C++23 draft [basic.start.main]:

6.9.3.1

    1. A program shall contain exactly one function called main that belongs to the global scope. Executing a program starts a main thread of execution ([intro.multithread], [thread.threads]) in which the main function 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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading