Search⌘ K
AI Features

Discussion: Weakly Typed, Strongly Puzzling

Explore the nuances of implicit type conversions in C++ through puzzle discussions. Understand how string literals convert to pointers and bool, how unary operators affect these values, and why certain seemingly odd behaviors occur in C++ code. This lesson helps you recognize compiler behaviors and encourages writing clearer, more maintainable C++ code by avoiding confusing implicit conversions.

Run the code

Now, it’s time to execute the code and observe the output.

C++ 17
#include <iostream>
int main()
{
std::cout << +!!"";
}

Understanding the output

Wait, what? Is this legal C++? What does it even mean, and why does it print 1?

While C++ is a statically typed language, it’s not particularly strongly typed. As we’ve seen throughout the course, C++ is, in fact, very eager to implicitly convert between types without explicitly telling it to. For instance, in the Aristotle’s Sum of Parts puzzle, we saw how the sum of two char types is not a char; in the A Strong Point puzzle, we saw how we should declare our constructors explicit to avoid them taking part in implicit conversions; and in the ...