Saturday, April 19, 2025

C++ Functions

Functions are peaces of code dedicated to getting some specific job done. They can produce imiddiate results as product (printing on screen, for example), or they can return values so other parts of program, other functions can grab those values and do something more with that.

Think about functions as dedicated workers in some firm that will do just one job perfectly and nothing else. They are like specialists.

In this case we will create function someFunction() that will just print one line "I am from someFunction". It's not enough to have function, we also need to use it in main section of our program.

In C++ functions we can create functions outside main() part of the program, just like in this example:

#include <iostream>
#include <cstdlib>

using namespace std;

void someFunction() {
    cout << "I am from someFunction" << endl;
}

int main() {

    someFunction();

    return 0;

}

Result:

I am from someFunction

Process returned 0 (0x0)   execution time : 0.200 s
Press any key to continue.

 We can have multiple functions that will do specific jobs, in this case secondFunction() will run Calculator on Windows machines.

Run this code:

#include <iostream>
#include <cstdlib>

using namespace std;

void someFunction() {
    cout << "I am from someFunction" << endl;
}

void secondFunction() {
    system("calc");
}

int main() {

    someFunction();
    secondFunction();

    return 0;

}

Many times it's useful to create functions that will call other functions, even multiple times. Don't forget semicolons after the end of function call:

#include <iostream>
#include <cstdlib>

using namespace std;

void someFunction() {
    cout << "I am from someFunction" << endl;
}

void multiple_run() {
    someFunction();
    someFunction();
    someFunction();
}

int main() {

    multiple_run();

    return 0;

}

Result:

I am from someFunction
I am from someFunction
I am from someFunction

Process returned 0 (0x0)   execution time : 0.021 s
Press any key to continue.

Functions that will do some direct operations will have void before their name, and functions that will return values to rest of the program will have data types as return types like int, char and so on. 

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...