"Control ends with a non-void function" with do {return result; } while (condition);

I have the following function (given example):

QByteArray DecompressBytes(const QByteArray& content){
  /* function body (with other return expressions) */

  do { return content; } while(content.size() != 0);
}

The last line was added for testing, replacing the macro used. Visual Studio does not see a problem with this code, but g ++ generates

warning: control reaches the end of the non-void function [-Wreturn-type]

Changing the last line to return content;cancels the warning.
My question is: why does the compiler behave this way and what should be the form of the code to avoid any warnings?

The last line was ASSERT_FAIL("must be unreachable", content)c ASSERT_FAIL, expanding into a template do { ... } while(false)with another macro replacing whileto disable non-bool expressions, so the resulting expression was like do { qt_assert_x("", "", 42); return content; } while(::helper::bool_verify(false));.

g++ 5.3.0, MinGW ( Qt).

: ( ), :

QByteArray DecompressBytes(const QByteArray& content){
  QByteArray decompressed; //no 'unused variable' warning
  do { return content; } while(content.size() != 0);
} //produces warning above

QByteArray DecompressBytes2(const QByteArray& content){
  //QByteArray decompressed;
  do { return content; } while(content.size() != 0);
} //doesn't produce warning

std::vector<char> DecompressBytes3(const std::vector<char>& content){
  std::vector<char> decompressed; //no 'unused variable' warning

  do { return content; } while(content.size() != 0);
} //does produce warning

std::vector<char> DecompressBytes4(const std::vector<char>& content){
  int decompressed; //unused variable warning is given

  do { return content; } while(content.size() != 0);
} //doesn't produce warning

, .

+4
1

. GCC 4.9.2 Wall ( qt)

#include <vector>

std::vector<int> foo(const std::vector<int>& v)
{
    do { return v; } while( v.size() != 0 );
}

int main() {std::vector<int> v; foo(v);}

clang 4.2.1. , - , , , .


: , OP GCC, clang " " DecompressBytes4().

, do-while . Dead-code , return.

, , , return.

, . , ! =)


PS - , .

+4

Source: https://habr.com/ru/post/1672569/


All Articles