简体   繁体   中英

How to declare variable in function arguments

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}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM