0

In my network-programming course, I've come across the following function, which initializes a struct of type _body:

_body f1(int pkg_type, int key_len, void* key, int value_len, void* value) {
    _body new_body; 
    new_body.key_len = 0;
    new_body.key = NULL;
    new_body.value_len = 0;
    new_body.value = NULL;
    return new_body; }

Another function than calls this function to initialize the struct given some conditions:

_body f2(void* pkg_body, another_struct pkg_header) {
_body new_body;
new_body = f1(pkg_header.pkg_type, pkg_header.key_len, (pkg_header.key_len) ? pkg_body : NULL, pkg_header.value_len, (pkg_header.value_len) ? pkg_body + pkg_header.key_len : NULL);
return new_body;}

Question: What does the line:

new_body = f1(pkg_header.pkg_type, pkg_header.key_len, (pkg_header.key_len) ? pkg_body : NULL, pkg_header.value_len, (pkg_header.value_len) ? pkg_body + pkg_header.key_len : NULL);

do exactly? How does it work and how can I understand it in terms of if conditions?

Note that I'm not providing explicit definitions of the structs and their values as my question is merely about understanding syntax.

cory
  • 13
  • 2

1 Answers1

2

Writing :

int variable = (is_random_check_true() ? 1 : 2)

Is the same as writing :

int variable;

if (is_random_check_true()) {
    variable = 1;
} else {
    variable = 2;
}

The ternary operator just "returns" a value, which can be used to do whatever you want it to do (store it in a variable in my case). But you can use it to pass different values to a function call, just like in your case.

Note that the 2 possible values returned by the ternary should have the same type, in your case void * and in mine int