0

Let's say we have the following a struct defined as follows:

struct
{
    int  month;
    int  day;
    int  year;
} date;

Could I somehow implement a function that took as an argument a struct of the same type as date, even though it hasn't been named explicitly? In other words, would I be able to make a function call to some random function like randomFunction (date)? In that case, how would the header of that function look like, since there is no name for the struct type of date?

Thanks in advance :)

Andrés
  • 51
  • 1
  • 5
  • Look to `...` or pass by its address. – chux - Reinstate Monica Mar 29 '16 at 21:22
  • Possible duplicate of [Forward declaring a typedef of an unnamed struct](http://stackoverflow.com/questions/10249548/forward-declaring-a-typedef-of-an-unnamed-struct) – πάντα ῥεῖ Mar 29 '16 at 21:23
  • 1
    dupe/related: http://stackoverflow.com/questions/10040369/how-to-receive-unnamed-structures-as-function-parameters-in-c – NathanOliver Mar 29 '16 at 21:25
  • Think yourself: How would you declare the function parameter to pass the `struct`? And how would the compiler know about the members? – too honest for this site Mar 29 '16 at 21:27
  • @chux: `...`? How would you invoke `va_arg`? – Keith Thompson Mar 29 '16 at 21:47
  • @Keith Thompson OP has not detailed what the function is to do, so `va_arg()` and the oddities of using it with `Rivero_foo()` are TBD and if possible and/or if needed. As it stands, OP can use `printf("", data);` with no ill effects. Such a call can be useful to _use_ data in code to preserve from from being optimization out. Maybe it is a an embedded copy right notice, etc. – chux - Reinstate Monica Mar 29 '16 at 22:03
  • @chux: Whatever problem the OP is having, it's vanishingly unlikely that passing the anonymous struct to a variadic function is the solution. Naming the struct is almost certainly what the OP needs to do. – Keith Thompson Mar 29 '16 at 22:06

2 Answers2

1

You can define the struct type for date and call it within the program by using date

typedef struct date{
    int  month;
    int  day;
    int  year;
} date;
jackotonye
  • 3,537
  • 23
  • 31
0

There are ways to do it indirectly (for example you could pass a void* pointer that points to an object of the type, and then somehow access the members of the structure within the function).

A variadic function declared with , ... wouldn't work, since you still have to specify the name of the type when invoking va_arg().

No, there's no direct way to do that. A function parameter has to be of some named type. And none of the indirect ways of doing it, frankly, are worth doing.

If you want to pass an argument of some struct type to a function, just give the type a name.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631