Previous Lecture lect05 Next Lecture

lect05, Tue 04/16

User Input; Functions

User Input

Example of using command line arguments

int main(int argc, char *argv[]) {
// cline.cpp
#include <iostream>
#include <cstdlib>

using namespace std;

int main(int argc, char *argv[]) {

	cout << "Number of arguments: " << argc << endl;

	cout << argv[0] << endl;
	cout << argv[1] << endl;
	cout << argv[2] << endl;

	// how to use these arguments as numbers?
	// We can convert them using the atoi function
	// in the cstdlib standard library

	int x = atoi(argv[1]) + atoi(argv[2]);
	cout << x << endl;
	return 0;
}

As you can see, the program expects three input arguments to the program:

    ./cline 1 2 3

If you don’t provide the correct number of arguments, you will get a segmentation fault, since the computer will be accessing the uninitialized parts of the memory. It is always best to check that the provided number of arguments matches what the program expects. Here’s the updated version of the above code:

#include <iostream>
#include <cstdlib>

using namespace std;

int main(int argc, char *argv[]) {
    int num_args = 4;

	cout << "Number of arguments: " << argc << endl;
	if (argc == num_args)
	{
		cout << argv[0] << endl;
		cout << argv[1] << endl;
		cout << argv[2] << endl;
		// how to use these arguments as numbers?
		// We can convert them using the atoi function
		// in the cstdlib standard library

		int x = atoi(argv[1]) + atoi(argv[2]);
		cout << x << endl;
	}
	else
	{
		//cout << "You need to provide 3 arguments after the name of the program.\n";
        // Subtract one to eliminate the first argument, which is the name of the program
		cout << "You need to provide " << (num_args - 1) << " arguments after the name of the program.\n";
	}
	return 0;
}

Functions

Function Declarations

In C++, a function declaration must occur BEFORE they are used. * We can write the method after it is used, we just need to declare it. * Declaration must include: [return type] [function name] (input parameters) * Basically just the header of the function (its “signature”), followed by a semicolon * It is possible to leave out a function declaration, if you can place the entire function definition (the body) before the main(), but this is not common because it is often impractical to bury the main() function at the end of a file.

Example: Simple Function Definition

#include <iostream>

using namespace std;

int areaOfSquare(int length); // declaration

int main() {
	int result = areaOfSquare(20); // call
	cout << result << endl;
	return 0;
}

int areaOfSquare(int length) { // definition
	return length * length;
}
// OK. Function declaration happens before it was used

-----------
#include <iostream>

using namespace std;

int main() {
	int result = areaOfSquare(20); // call
	cout << result << endl;
	return 0;
}

int areaOfSquare(int length) { // definition
	return length * length;
}
// ERROR! use of undeclared identifier 'areaOfSquare'

Return vs. Print

Example of printing, but not returning

void printAreaOfSquare(int area) {
	cout << “Area of Square: “ << area << endl;
	return; // return not necessary, will exit function when reached.
}

Memory Stack

Example

#include <iostream>

using namespace std;

int doubleValue(int x) {
	return 2 * x;
}

int quadrupleValue(int x) {
	return doubleValue(x) + doubleValue(x);
}

int main() {
	int result = quadrupleValue(4);
	cout << result << endl;
	return 0;
}
|                       |
|-----------------------|
| int main()            |
|_______________________|
|                       |
|-----------------------|
| int quadrupleValue(4) |
|-----------------------|
| int main()            |
|_______________________|
|                       |
|-----------------------|
| int doubleValue(4)         |
|-----------------------|
| int quadrupleValue(4) |
|-----------------------|
| int main()            |
|_______________________|
|                       |
|-----------------------|
| int quadrupleValue(4) |
|-----------------------|
| int main()            |
|_______________________|
|                       |
|-----------------------|
| int doubleValue(4)         |
|-----------------------|
| int quadrupleValue(4) |
|-----------------------|
| int main()            |
|_______________________|
|                       |
|-----------------------|
| int quadrupleValue(4) |
|-----------------------|
| int main()            |
|_______________________|
|                       |
|-----------------------|
| int main()            |
|_______________________|

Code written during lecture

The example shows how to do function overloading. Not included is the example of a function with the same input parameters but different return types, which results in an error.

// print_hello.cpp
#include <iostream>
#include <cstdlib>
using namespace std;

double return_sum(double var, double x)
{
       return (var+x);
}

void print_hello(int var, int x)
{
    for (int i = 0; i < var; i = i+x)
    {
        cout << "Hello" << endl;
        cout << "var = " << var << " x = " << x << endl;
    }
    return;
}


void print_hello(int var)
{
    for (int i = 0; i < var; i++)
    {
        cout << "Hello" << endl;
    }
    return;
}

void print_hello()
{
    cout << "Hello" << endl;
    return;
}

int main(int argc, char* argv[])
{
    int user_count = -1;

    if (argc == 1)
    {
        cout<< "The name of your program is " << argv[0] << endl;
        return 0;
    }
    if (argc == 2)
    {
        user_count = atoi(argv[1]);
    }
    else {
        cout << "You didn't give us correct input!" << endl;
        exit(-1);
    }


    print_hello(user_count);

    cout << "___" << endl;
    print_hello(5, 2);

    cout << "___" << endl;
    cout << return_sum(15.5, 12.8) << endl;

    return 0;
}

Practice Questions

  1. Can you have return statements in a void function?
  2. Create a function named root that accepts 3 inputs of type double as parameters, and returns a double, based on the following conditions:
    • Pre-condition: There are 3 input parameters, all 3 of type double, that represents as a, b, c from a quadratic equation.
    • Post-condition: Returns ONE OF THE solutions from the quadratic formula. The function prints an error message if there are no real roots, and exits.
    • Assume the cmath library from the C++ Standard Libraray is available for you.
  3. What’s wrong with the following code?
    int main(int argc, char* argv[]){
     int x = argv[1];
     cout << x * 2 << endl;
    }