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.
It is a GCC extension:
6.23 Arithmetic on
void- and Function-PointersIn 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
voidor of a function as 1.A consequence of this is that
sizeofis also allowed onvoidand 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]returns1at any value ofi.
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.)
User contributions licensed under CC BY-SA 3.0