4

According to stack overflow, The [[noreturn]] attribute specifies that a function does not return. Ok, thats fine.

But I don't understand how to use [[noreturn]] attribute in program. I tried to use [[noreturn]] attribute in my code. But when I compiled my code in GCC compiler, I got following error.

error: expected unqualified-id before ‘[’ token
 [[noreturn]] void f(int i) {
 ^
cp1.cpp: In function ‘int main()’:
cp1.cpp:11:6: error: ‘f’ was not declared in this scope
  f(10);

My code is here:

#include <cstdlib>

[[noreturn]] void f(int i) {
  if (i > 0)
    throw "Received positive input";
  std::exit(0);
}

int main()
{
        f(10);
}

How to use [[noreturn]] attribute in C++?

Community
  • 1
  • 1
msc
  • 33,420
  • 29
  • 119
  • 214

2 Answers2

4

You are definitely using a non-compliant C++11 compiler or a pre-C++11 compiler, or your flags isn't set to -std=c++11? (at least).

If you are stuck with pre-C++11 compilers, you can wrap up a simple macro that uses built-in compiler attributes in a hopefully portable way:

#ifdef __GNUC__
#define NO_RETURN __attribute__((noreturn))
#elif __MINGW32__
#define NO_RETURN __attribute__((noreturn))
#elif __clang__
#define NO_RETURN __attribute__((noreturn))
#elif _MSC_VER
#define NO_RETURN __declspec(noreturn)
#endif

And then use as:

NO_RETURN void f(int i) {
  if (i > 0)
    throw "Received positive input";
  std::exit(0);
}
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
0

I think maybe the attribute was not supported by the compiler then, It was passed now, Here are my gcc version: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 Copyright (C) 2019 Free Software Foundation, Inc.

Jamishon
  • 72
  • 7