C ++ and the preprocessor macro

Can you figure out what is wrong with the statement below?

GCC Error Status:

'type name' declared as function return array

#define MACRO(a) (a)[1] class index { public: typedef int index_type[2]; const index_type& operator[](int i) const; }; int k = 0; int i = MACRO(index()[k]); 

btw: I know what's wrong, I thought it was a funny thing. Many thanks to the light bulb, its explanation of the previous information helped to quickly resolve this error.

+4
source share
3 answers

In the extended line:

 int i = (index()[k])[1]; 

(index()[k]) interpreted as a cast expression declaring a function that returns an array of length k index. At least what it looks like is happening. How gcc can correctly interpret [1] as an expression, I'm not sure.

+4
source

My guess would be there ambiguities in your syntax. The compiler can see the extended macro:

  int i = (index()[k])[1]; 

And thinking that index is actually a non-member function declaration that returns an array, rather than creating a temporary object of type index .

But this is just an assumption ... if you already know the answer, please enlighten us :)

+2
source

When applying a macro, it expands to:

 class index { // ... typedef int index_type[2]; const index_type& operator[](int i)const; // ... }; int k = 0; int i = (index()[k])[1]; 

Now the problem is (assuming that index :: operator [] is public, and this is not obvious from your code fragment), so the result of index :: operator [] is returned by reference, and you build the index () object as temporary, and therefore, assuming your index :: operator [] is implemented, as I assume you have implemented it (returning a link to a member object), the result of index :: operator [] will be invalid immediately after it returns (since the temporary is destroyed), and therefore you have undefined behavior.

+1
source

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


All Articles