Introduction to Programming and C++

Contents Previous Topic Next Topic

In this lesson, we'll look at common ways of making something as simple as a return statement clearer.

Example 1

So often in beginner's code, you will see functions which return a bool which look like:

bool f( ... ) {
	// do stuff

	if ( array_size == 0 ) {
		return true;
	} else {
		return false;
	}
}

Because the == check already returns true or false, you can just return that value, as demonstrated here:

bool f( ... ) {
	// do stuff

	return ( array_size == 0 );
}

This is often clearer than an if statement.

Example 2

A similar construction can be made where a function returns two possible values based on a Boolean result. Consider the max function:

int max( int n, int m ) {
	if ( n >= m ) { 
		return n;
	} else {
		return m;
	}
}

While this is acceptable, it can be written much more compactly as

int max( int n, int m ) {
	return ( n >= m ) ? n : m;
}

Example 3

In some cases, using ?: may lead to confusion:

int max( int a, int b, int c ) {
	return ( a >= b && a >= c ) ? a : (b >= c) ? b : c;
}

Did you catch that? Perhaps if I rewrite it:

int max( int a, int b, int c ) {
	return ( a >= b && a >= c ) ? a : (
		(b >= c) ? b : c
	);
}

The second form is almost acceptable: with everything on one line, it is difficult to follow. In the second, the first and second operands of ?: are clear and the third, the more complex argument, is on a line of its own, but still clearly connected to the previous statement.


Questions

1. Write an double abs( double x ) function which returns the absolute value of the argument x. You should do this with a single return statement.

2. Write a unit-step double step( double x, double bound ) function which returns 0.0 if x <= bound and 1.0 otherwise. You should do this with a single return statement.

3. What is wrong with the following statement?

bool is_large( double x ) {
	return ( x < -5.0 || x > 5.0 ) ? true : false;
}

Contents Previous Topic Top Next Topic