Example 4

Example 4 demonstrates the principle of least surprise as follows:

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

int main(void)
{
printf("The answer is: %d ", 42);
std::cout << "The answer is: " << 42 << ' ';
return 0;
}

As shown in the preceding example, another great example of the principle of least surprise is the difference between printf() and std::cout. The printf() function requires the addition of format specifiers to output integers to stdout. There are many reasons why printf() is not intuitive:

  • To a beginner, the printf() function's name, which stands for print formatted, is not intuitive (or in other words, the function's name is not self-documenting). Other languages avoid this issue by picking more intuitive names for a print function, such as print() or console(), which do a better job of adhering to the principle of least surprise.  
  • The format specifier symbol for an integer is d. Once again, to a beginner this is unintuitive. In this specific case, d stands for decimal, which is another way of saying signed integer. A better format specifier might have been i to match the language's use of int

Contrast this with std::cout, which stands for character output. Although this is less intuitive compared to print() or console(), it is more intuitive than printf(). Furthermore, to output an integer to stdout, the user doesn't have to memorize a table of format specifiers to complete their task. Instead, they can simply use the << operator. Then, the APIs handle formatting for you, which is not only more intuitive but also safer (especially when working with std::cin as opposed to scanf()). 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset