skip to content

In GoogleTest, why can EXPECT_EQ give the wrong verdict for C strings and doubles, and which assertions should replace it?

level: middleimportance: should knowfreq 58%

answer

  1. what == means for char pointers
  2. same text, different address
  3. units in the last place
  4. an absolute bound near zero

basics

~10 s

EXPECT_EQ uses ==, which compares addresses for C strings and exact bits for doubles. Use EXPECT_STREQ for C strings and EXPECT_DOUBLE_EQ, EXPECT_FLOAT_EQ or EXPECT_NEAR for floating-point values.

solid answer

~40 s

`EXPECT_EQ` simply applies `==`. On two `const char*` values that is **pointer equality**: two buffers holding "2026" at different addresses compare unequal, and the failure prints two addresses. `EXPECT_STREQ` and `EXPECT_STRNE` compare characters, `EXPECT_STRCASEEQ` ignores case, and comparing an `std::string` with `EXPECT_EQ` is fine because its `operator==` compares contents. For floating point, `0.1 + 0.2 == 0.3` is false, so exact comparison fails on rounding. `EXPECT_DOUBLE_EQ` and `EXPECT_FLOAT_EQ` accept values within **4 ULPs** of each other, which suits values that should be the same computation; `EXPECT_NEAR(a, b, abs_error)` takes an explicit bound and is the right tool near zero, where a 4-ULP window is far too small.

code

cpp · 18 lines
cpp
#include <gtest/gtest.h>
#include <string>

TEST(DateFieldTest, CStringsAndDoubles) {
  char parsed[] = "2026";
  const char* expected = "2026";
  EXPECT_EQ(parsed, expected);               // compares addresses: fails
  EXPECT_STREQ(parsed, expected);            // compares characters: passes
  EXPECT_EQ(std::string(parsed), expected);  // std::string ==: passes

  double fraction = 0.1 + 0.2;               // e.g. a fraction of a day
  EXPECT_EQ(fraction, 0.3);                  // exact ==: fails
  EXPECT_DOUBLE_EQ(fraction, 0.3);           // within 4 ULPs: passes
  EXPECT_NEAR(fraction, 0.3, 1e-9);          // explicit bound: passes

  EXPECT_DOUBLE_EQ(1e-17, 0.0);              // ULPs near zero: fails
  EXPECT_NEAR(1e-17, 0.0, 1e-12);            // absolute bound: passes
}

go deeper

for a junior

Recall that EXPECT_EQ on C strings compares pointers and that EXPECT_STREQ compares text.

for a middle

Explain ULP-based comparison against an absolute bound and choose correctly between EXPECT_DOUBLE_EQ and EXPECT_NEAR, including the case near zero.

for a senior

Read a failure output and diagnose the mistake from it, and pick tolerances that reflect the code's documented accuracy rather than whatever makes the test pass.

for a principal

Set a convention for numeric tests, such as named tolerances tied to each algorithm's accuracy contract, so floating-point checks stay meaningful as the code evolves.

## EXPECT_EQ is just == GoogleTest's `EXPECT_EQ(val1, val2)` and `ASSERT_EQ(val1, val2)` verify `val1 == val2` with the operands' own `operator==`. That is exactly right for integers, enumerations, `std::string`, containers and your own types with a sensible equality. It is wrong for two kinds of value that interviewers like to probe: **C strings** and **floating-point numbers**. ## C strings: pointers, not text A C string is a `char` array or a `const char*`. Comparing two of them with `==` compares **addresses**, because an array decays to a pointer to its first element. The assertions reference states it plainly: `EXPECT_EQ` "does pointer equality on pointers". Two buffers that both contain `"2026"` live at different addresses, so the check fails, and the failure message prints two hexadecimal addresses rather than two strings, which is the giveaway. The string assertions compare contents: | Assertion | Passes when | |---|---| | `EXPECT_STREQ(s1, s2)` | the two C strings hold the same characters | | `EXPECT_STRNE(s1, s2)` | the contents differ | | `EXPECT_STRCASEEQ(s1, s2)` | the contents match ignoring case | | `EXPECT_STRCASENE(s1, s2)` | the contents differ ignoring case | They also accept wide C strings (`wchar_t*`). Two practical notes: - If either side is an `std::string`, plain `EXPECT_EQ` is correct, since `std::string`'s `operator==` compares characters. Wrapping one side, as in `EXPECT_EQ(std::string(buf), "2026")`, is a common fix. - To check a C string for null, the reference recommends `EXPECT_EQ(p, nullptr)` or `EXPECT_NE(p, nullptr)`, with `nullptr` rather than `NULL`. ## Floating point: exact bits rarely match Binary floating point cannot represent `0.1`, `0.2` or `0.3` exactly, so `0.1 + 0.2` is `0.30000000000000004` in an IEEE 754 `double`, the format every mainstream C++ implementation uses. `EXPECT_EQ(0.1 + 0.2, 0.3)` therefore fails, and GoogleTest prints the extra digits that show why. GoogleTest provides three floating-point assertions: 1. **`EXPECT_DOUBLE_EQ(a, b)`** passes when two `double` values are within **4 ULPs** (units in the last place) of each other. A ULP is the gap between adjacent representable values, so the tolerance scales with the magnitude of the numbers. 2. **`EXPECT_FLOAT_EQ(a, b)`** is the same rule for `float`. 3. **`EXPECT_NEAR(a, b, abs_error)`** passes when `|a - b|` does not exceed an **absolute** bound you choose. ## Choosing between ULPs and an absolute bound - Use `EXPECT_DOUBLE_EQ` when both sides are, in exact arithmetic, the same value reached by slightly different rounding, such as a fraction of a day computed two ways. - Use `EXPECT_NEAR` when the expected value is **zero or close to it**. Near zero, adjacent doubles are extremely close together, so a 4-ULP window is tiny: `EXPECT_DOUBLE_EQ(1e-17, 0.0)` fails, while `EXPECT_NEAR(1e-17, 0.0, 1e-12)` passes. - Use `EXPECT_NEAR` too when the code under test has a documented accuracy, such as an approximation that is good to `1e-6`; the bound states that contract in the test. Two edge cases are worth knowing. A NaN never compares equal, so `EXPECT_DOUBLE_EQ(nan, nan)` fails. In `EXPECT_NEAR`, two infinities of the same sign count as a difference of zero. ## Reading the failure output The output usually tells you which mistake you made. Two addresses under `Which is:` mean you compared pointers. A value printed as `0.30000000000000004` against `0.3` means you compared floating-point values exactly. GoogleTest prints each argument with its `<<` operator when one exists, which is why `std::string` and `double` values show up readably. ## Why not a hand-rolled check A common shortcut is `EXPECT_TRUE(std::abs(a - b) < 1e-9)`. It works, but on failure GoogleTest can only print that the expression was `false`; the two values and the difference are lost, so the first thing anyone does is add a print statement and re-run. `EXPECT_NEAR` states the same rule and prints the values, the difference and the bound. The same reasoning applies to C strings: `EXPECT_TRUE(std::strcmp(a, b) == 0)` hides both strings, while `EXPECT_STREQ(a, b)` prints them. For rarer floating-point relations GoogleTest offers predicate-format functions rather than more macros: `EXPECT_PRED_FORMAT2(testing::DoubleLE, a, b)` verifies that `a` is less than, or approximately equal to, `b`, and `testing::FloatLE` does the same for `float`. Matcher-based comparisons with `EXPECT_THAT` exist too and are covered with the mocking material. ## Summary of the rule - Text in `char` buffers: `EXPECT_STREQ` and friends, or convert one side to `std::string`. - Results of floating-point arithmetic: `EXPECT_DOUBLE_EQ` or `EXPECT_FLOAT_EQ` for "the same value", `EXPECT_NEAR` with a stated tolerance otherwise. - Everything else with a meaningful `operator==`: `EXPECT_EQ`.

  • Why does EXPECT_DOUBLE_EQ fail when comparing 1e-17 with 0.0?
    Because a 4-ULP window scales with magnitude. Around zero the representable doubles are packed extremely densely, so 1e-17 is a vast number of ULPs away from 0.0 even though it is tiny in absolute terms. When the expected value is zero, state an absolute tolerance with `EXPECT_NEAR(value, 0.0, bound)`.
  • How do you compare two std::string objects, or an std::string with a string literal?
    With `EXPECT_EQ`. `std::string`'s `operator==` compares characters, including against a `const char*`, so pointer identity never enters into it. The C-string assertions are for the case where both sides are raw `char` pointers or arrays.

  • EXPECT_EQ on two const char* compares the characters they point to.
  • EXPECT_DOUBLE_EQ compares with a fixed absolute tolerance such as 1e-9.
  • EXPECT_STREQ must be used for std::string objects too.
  • EXPECT_NEAR(a, b, eps) is a percentage-based relative comparison.
  • Two NaN values pass EXPECT_DOUBLE_EQ because they have the same bits.