Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.
PrevUpHomeNext

Strings and C-strings comparison

In the general case, pointers are compared using their value. However when type of the the pointers are char* or wchar_t*, BOOST_TEST promotes them as null terminated char arrays and string comparison is used instead. std::string (or any std::basic_string) is eligible for string comparison.

String comparison can be used only if the the operands to compare in BOOST_TEST can both be considered as strings type.

[Tip] Tip

In this form, the comparison method and reporting can be overridden an additional argument to BOOST_TEST. See the collection comparison section for more details, in particular boost::test_tools::per_element() and boost::test_tools::lexicographic() modifiers.

Example: BOOST_TEST string comparison

Code

#define BOOST_TEST_MODULE boost_test_strings
#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_CASE( test_pointers )
{
  float a(0.5f), b(0.5f);
  const float* pa = &a, *pb = &b;
  BOOST_TEST(a == b);
  BOOST_TEST(pa == pb);
}

BOOST_AUTO_TEST_CASE( test_strings )
{
  const char* a = "test1";
  const char* b = "test2";
  const char* c = "test1";
  BOOST_TEST(a == b);
  BOOST_TEST(a == c);
  BOOST_TEST(std::string("test1") == b);
  BOOST_TEST(std::string("test1") < a, boost::test_tools::per_element());
  BOOST_TEST(b < a, boost::test_tools::lexicographic());
}

Output

> ./boost_test_strings
Running 2 test cases...
test.cpp:17: error: in "test_pointers": check pa == pb has failed [0x7fff54f9dea4 != 0x7fff54f9dea0]
test.cpp:25: error: in "test_strings": check a == b has failed [test1 != test2]
test.cpp:27: error: in "test_strings": check std::string("test1") == b has failed [test1 != test2]
test.cpp:28: error: in "test_strings": check std::string("test1") < a has failed
Mismatch at position 0: 't' >= 't'.
Mismatch at position 1: 'e' >= 'e'.
Mismatch at position 2: 's' >= 's'.
Mismatch at position 3: 't' >= 't'.
Mismatch at position 4: '1' >= '1'.
test.cpp:29: error: in "test_strings": check b < a has failed
Failure at position 4: '2' >= '1'.

*** 5 failures are detected in the test module "boost_test_strings"

PrevUpHomeNext