Saturday, April 19, 2025

C++ Functions With Arguments

We can pass values to function so function can grab them and use for some operations.

When we declare or define functions, in between parentheses, we will state type and name for parameters/arguments.

For example, we have function here funcName(int x) that will demand some integer as input.

Lowercase "x" will represent any number that we will pass. You can use any character here, just use something abstract for simple stuff, or some word that will describe what is happening.

A task for function is simple here, it will just print that value on screen.

Down in main() section of program, we are calling function funcName() with input 40.

Run this code:

#include <iostream>
#include <cstdlib>

using namespace std;

void funcName(int x) {
    cout << "x at this moment of time: " << x << endl;
}

int main() {

    funcName(40);

    return 0;

}

Result:

x at this moment of time: 40

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

Naturally, we can call same function multiple times with same or different arguments:

#include <iostream>
#include <cstdlib>

using namespace std;

void funcName(int x) {
    cout << "x at this moment of time: " << x << endl;
}

int main() {

    funcName(40);
    funcName(424654);
    funcName(1231321);

    return 0;

}

Result:

x at this moment of time: 40
x at this moment of time: 424654
x at this moment of time: 1231321

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

Inside main() program section we will create a container that will hold value from a keyboard so we can pass it to function.

Because x must be an integer while calling function, container must be of same data type:

#include <iostream>
#include <cstdlib>

using namespace std;

void funcName(int x) {
    cout << "x at this moment of time: " << x << endl;
}

int main() {

    int container;

    cout << "Please, enter just integer: " << endl;
    cin >> container;

    funcName(container);

    return 0;

}

Result when we enter integer 50:

Please, enter just integer:
50
x at this moment of time: 50

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

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 .  ...