From e5eb871419fc80799a8126fefe147d8fb4a04a2f Mon Sep 17 00:00:00 2001 From: Jiakai Liu Date: Fri, 22 Mar 2019 14:01:41 -0700 Subject: [PATCH] Fix DCHECK to handle dangling else (#18295) Summary: Pull Request resolved: https://github.com/pytorch/pytorch/pull/18295 Replace "if (false)" with "while (false)" which fixes potential dangling else issue as shown in added test case. Reviewed By: ezyang Differential Revision: D14569608 fbshipit-source-id: 407052db9182ce27b7a59841e90fa50d3eca262e --- c10/test/util/logging_test.cpp | 7 +++++++ c10/util/logging_is_not_google_glog.h | 16 ++++++++-------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/c10/test/util/logging_test.cpp b/c10/test/util/logging_test.cpp index e05d781..38f7787 100644 --- a/c10/test/util/logging_test.cpp +++ b/c10/test/util/logging_test.cpp @@ -77,6 +77,13 @@ TEST(LoggingTest, Join) { EXPECT_EQ(s, "1, 2, 3"); } +TEST(LoggingTest, TestDanglingElse) { + if (true) + DCHECK_EQ(1, 1); + else + GTEST_FAIL(); +} + #if GTEST_HAS_DEATH_TEST TEST(LoggingDeathTest, TestEnforceUsingFatal) { bool kTrue = true; diff --git a/c10/util/logging_is_not_google_glog.h b/c10/util/logging_is_not_google_glog.h index 8d8f7f6..50b0c0d 100644 --- a/c10/util/logging_is_not_google_glog.h +++ b/c10/util/logging_is_not_google_glog.h @@ -120,7 +120,7 @@ static_assert( #else // Optimized version - generates no code. #define DCHECK(condition) \ - if (false) \ + while (false) \ CHECK(condition) #endif // NDEBUG @@ -146,22 +146,22 @@ static_assert( #else // !NDEBUG // These versions generate no code in optimized mode. #define DCHECK_EQ(val1, val2) \ - if (false) \ + while (false) \ CHECK_OP(val1, val2, ==) #define DCHECK_NE(val1, val2) \ - if (false) \ + while (false) \ CHECK_OP(val1, val2, !=) #define DCHECK_LE(val1, val2) \ - if (false) \ + while (false) \ CHECK_OP(val1, val2, <=) #define DCHECK_LT(val1, val2) \ - if (false) \ + while (false) \ CHECK_OP(val1, val2, <) #define DCHECK_GE(val1, val2) \ - if (false) \ + while (false) \ CHECK_OP(val1, val2, >=) #define DCHECK_GT(val1, val2) \ - if (false) \ + while (false) \ CHECK_OP(val1, val2, >) #endif // NDEBUG @@ -178,7 +178,7 @@ static_assert( #else // !NDEBUG // Optimized version - generates no code. #define DCHECK_NOTNULL(val) \ - if (false) \ + while (false) \ CHECK_NOTNULL(val) #endif // NDEBUG -- 2.7.4