Why does the subscript operator at any index on a function always returns 1 in C++?

-4

This is my code. It seems that f[i] returns 1 at any value of i.

int f(int x) { return 203; }

int main(){
  cout<<f[0]<<' '<<f[21]<<' 'f[-1];//= 1 1 1
  return 0;
}

Using the warning thrown by the compiler I understand that this is a pointer but it doesn't seem to behave like one.

f[-2](1) // = 203, good
f[32](1) // Process returned -1073741571 (0xC00000FD)   execution time : 6.731 s

EDIT: I use the g++ compiler with the c++ 14 flag.

c++
pointers
function-pointers
asked on Stack Overflow Jul 14, 2018 by Ivanov Mihai Cosmin • edited Jul 14, 2018 by Ivanov Mihai Cosmin

1 Answer

2

It is a GCC extension:

6.23 Arithmetic on void- and Function-Pointers

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1.

A consequence of this is that sizeof is also allowed on void and on function types, and returns 1.

Resulting pointers to non-existent functions, if called, would most likely crash or produce weird results.


It seems that f[i] returns 1 at any value of i.

That's a well-known behaviour of cout. It prints all non-zero function pointers as 1, because there is no proper overload of operator<< for them, and operator<<(bool) gets chosen as a most suitable overload.

(f[i] is a function rather than a function pointer, but it decays to a pointer in this case.)

answered on Stack Overflow Jul 14, 2018 by HolyBlackCat

User contributions licensed under CC BY-SA 3.0