Why do I get a type mismatch error in C++?
Common Causes
Type mismatches often happen when you mix signed and unsigned integers, use the wrong pointer type, or forget to include a header that declares a function. For example, assigning a double to an int variable without a cast triggers a narrowing conversion warning or error.
Another frequent cause is calling a function with arguments that don't match its parameter types, such as passing an int where a std::string is expected. Template code can also produce confusing mismatch errors if the deduced types don't align.
- Assigning a floating-point value to an integer variable without a cast.
- Passing a pointer of one type to a function expecting a different pointer type.
- Using an undeclared function, leading to an implicit declaration error.
- Mixing signed and unsigned types in comparisons or arithmetic.
- Forgetting to include the header that defines a class or function.
How to Fix It
First, read the compiler error message carefully—it often points to the exact line and the types involved. Then check the types of the variables or expressions on both sides of the assignment or function call.
If a conversion is safe, use an explicit cast like static_cast<int>(someDouble). If not, change the variable type or the function signature to match. For function calls, ensure you're passing the correct number and types of arguments, and that all necessary headers are included.
Common mistakes
- Assuming the error is always about the line where it's reported—sometimes the real issue is earlier in the code.
- Ignoring compiler warnings about implicit conversions, which can later become hard-to-find bugs.
- Using C-style casts instead of C++ casts, which can hide unsafe conversions.
