Reputation: 134
I need to declare a variable inside function arguments. Please advice the syntax to use?
I've got something like this:
#include <stdio.h>
int foo (int *a)
{
printf ("%d\n", *a);
}
int main (void)
{
foo (&(int){int a=1});
return 0;
}
And GCC fails with the message:
$ gcc a.c
a.c: In function 'main':
a.c:10: error: expected expression before '{' token
As an option I can put use not named variable like this (same question at russian version of Stack Overflow):
foo(&(int) { 1 });
and it works, but it is interesting why compiler accept {1}
but does not accept {int a=1}
Upvotes: 0
Views: 107
Reputation: 213689
You can use compound literal - I suspect that's what you tried, you almost got it right:
foo (&(int){1});
This is by no means a "constant", I don't know how you got that idea.
Note that a compound literal only have local ("automatic") storage duration - if the calling block goes out of scope, so does the compound literal.
Upvotes: 3