Dev Notes

Software Development Resources by David Egan.

Conditional Printing in C and C++ Using a Ternary Statement


C, C++
David Egan

This article contrasts how output to stdout differs between C++ and C (std::cout and printf()). In particular, we’re looking at conditional output that includes variables.

C++ Stream Out Operator

The << operator in C++ is the stream insertion operator and it is used to push data into the std::out output stream.

This allows you to print to stdout like this:

#include <iostream>

int main(void)
{
	std::cout << "Hello World!\n";
	return 0;
}

std::cout figures out how to output variables - you can just feed them in and it works automagically:

float price = 10.99;
char *name = "Cheddar";
std::cout << "The price of " << name << " is " << price << '\n';
// Outputs: The price of Cheddar is 10.99

The printf() Function

The printf() function uses placeholders to insert variable values into a string for output to stdout:

#include <stdio.h>

int main(void)
{
	float price = 10.99;
	char *name = "Cheddar";
	printf("The price of %s is %f.\n", name, price);
	return 0;
}

You need to be careful to use the correct conversion specifiers in the placeholder. These are determined by the type of data to be inserted. In the example above, %s denotes a string placeholder and %f denotes a float placeholder.

Python 3 gives you the best of both worlds with the string method format(), which allows you to insert unspecified data types into placeholders within the output string.

Conditional Output

If you want to output content that is conditional, you can embed ternary statements within the C++ std::cout output stream:

int cheese = 0;

// Example of a simple ternary with output stream operators.
std::cout << (cheese ? "We have cheese." : "+++Out of Cheese Error+++") << std::endl;

If you want to embed variables in your conditonal output stream, this method doesn’t work. As far as I can tell, you need to employ an if/else block.

By way of contrast, it’s pretty easy to embed variables within a ternary statement using printf().

In the following example the objective is to let the user know the level of cheese if the level of cheese is greater than zero, but to display a warning if the level of cheese is zero.

The example is C++, but the printf() statements are valid in C.

#include <iostream>
#include <stdio.h>

int main(void)
{
	int cheese = 0;

	// This achieves what we need, but is pretty verbose:
	if (cheese)
		std::cout << "Cheese level: " << cheese << '\n';
	else
		std::cout << "+++Out of Cheese Error+++\n";

	// Format string the same for both conditions - not a good solution
	// since '0' is printed in the empty case.
	printf("%s%d\n", (cheese ? "Cheese level: " : "+++Out of Cheese Error+++"), cheese);
	
	// Better solution - choose the format string in a ternary statement
	printf(cheese ? "Cheese level: %d\n" : "+++Out of Cheese Error+++\n", cheese);
	
	return 0;
}

comments powered by Disqus