简体   繁体   中英

A way to emulate named arguments in C

Is there a way to use named arguments in C function?

Something like function with prototype void foo(int a, int b, int c);

and I want to call it with foo(a=2, c=3, b=1);[replaced the order of b & c and used their names to distinguish]

Motivation: I want a more Pythonic C, where I can easily manipulate my function arguments without mixing them by mistake

Kinda, sorta, with a compound literal and designated initializers:

typedef struct foo_args {
  int a;
  int b;
  int c;
} foo_args;

// Later

foo(&(foo_args) {
  .a = 2,
  .c = 3,
  .b = 1
});

But I honestly wouldn't bother. It requires you to bend the function definition to accept a pointer, and makes calling it cumbersome.

Named arguments are not supported in C.

All arguments must be passed in the correct order.

C does not support keyword/named arguments. If you try foo(a=2, c=3, b=1); C compiler will flag "identifier 'a' is undefined". It is a syntax error. It expects tokens a, b, c declared beforehand

int a = 2; int b = 1; int c = 3; // order doesn't matter here.
foo(a, b, c); 

or pass by value directly

foo(2, 1, 3) // positional arguments. 

My guess is that C compiler is not as sophisticated as Python's interpreter. Python is a dynamically typed language and able to push the keyword arguments onto stack. You can pick more descriptive names for the parameters without referring to an IDE:

int volume(height, width, depth)
{ return height * width * depth; }

Personally, I see this Python feature confusing. For instance:

>>> def foo(a, b, c):   pass
...
>>> foo(c=3, b=1, a=2)
>>> foo(a=2, c=3, 1)
  File "<stdin>", line 1
    foo(a=2, c=3, 1)
                   ^
SyntaxError: positional argument follows keyword argument
>>> foo(2, c=3, b=1)
>>> foo(2, 3, 1)
>>> foo(2, c=3, a=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got multiple values for argument 'a'
>>>
There are certain rules you have to observe when mixing keyword with positional arguments.

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