Home > Enterprise >  Why calling a function from shorthand function pointers array initialization doesn't compile?
Why calling a function from shorthand function pointers array initialization doesn't compile?

Time:05-10

I have the following code in my project:

printf("Please select one of the tests: ");
int n;
scanf("%d", &n);
(void (* [])()) {test1, test2, test3, test4}[n - 1]();

For me, this code compiles and works as indented. But my professor said that this doesn't compile for her.

I write code compliant with the C23 standard and my compiler is Apple Clang v13.0.0. But about my professor, all I know is that she uses the MSVC compiler; I have no information on either the compiler version or the standard she marks the code with.

I tried changing the C standard to C99 and it still worked, so I think this has to be a compiler issue. I don't have a Windows machine to play around with MSVC and test whether the problem is the anonymous array initialization, the subscript operator immediately after it, the call operator after the entire thing, or something else entirely.

Now, of course I know that I can declare an array of function pointers first, and then assign every element, or just use a switch for this purpose. I also know that this is a kind of "clever code" that may not be welcome in actual projects maintained by more people, but this is my code, created for educational purposes only. Also, my professor likes this kind of "clever tricks" as extreme examples of what can you do with the language. What I do like to know is what could be the reason this code does not compile with MSVC. Is that syntax some compiler-specific language extension or is it just Microsoft which, as always, is not keeping up with support for all language features?

CodePudding user response:

Your teacher is probably compiling your code as C .

With dummy functions added, if this code is placed in a .c file and compiled with MSVC 2015, it compiles fine. If the file has a .cpp extension, it generates the following errors:

x1.cpp(13): error C3260: ')': skipping unexpected token(s) before lambda body
x1.cpp(13): error C2143: syntax error: missing ';' before '}'
x1.cpp(13): warning C4550: expression evaluates to a function which is missing an argument list
x1.cpp(13): error C2676: binary '[': 'main::<lambda_8caaf9f5b122025ad6cda2ca258a66a7>' does not define this operator or a conversion to a type acceptable to the predefined operator
x1.cpp(13): error C2143: syntax error: missing ')' before ';'
x1.cpp(13): error C2059: syntax error: ';'

So it thinks your compound literal is a lambda function. Compound literals are a C-only construct, so unless your C compiler supports them as an extension it won't work.

Have your teacher compile your code as C by putting it in a file with a .c extension.

Alternately, don't use a compound literal. Create the array first, then index it and call the function.

void (*f[])() = {test1, test2, test3, test4};
f[n - 1]();
  • Related