简体   繁体   中英

Evaluating a struct inside of a conditional statement in C

Is there a way to evaluate a struct variable inside of a conditional statement as a whole such that each element does not need to be written out? For example given the following struct:

typdef struct
{
    int a;
    int b;
    int c;
} number;

number foo = {1, 2, 3};

I would like to evaluate the elements in an if statement such as:

if (foo.a == 1 && foo.b == 2 && foo.c == 3)
{
    ...
} 

However, I want to evaluate the entire struct without having to list individual elements. I know this is not correct but this is along the lines of what I want to accomplish:

if (foo == {1, 2, 3})
{
    ...
}

Your help is greatly appreciated. Thanks.

You can represent a temporary struct through a compound literal

(number) { 1, 2, 3 }

so a more logical attempt would look as

if (foo == (number) { 1, 2, 3 })
  ...

but it won't work, since C language does not provide a built-in operator for comparison of struct objects. You can use memcmp instead

if (memcmp(&foo, &(number) { 1, 2, 3 }, sizeof foo) == 0)
  ...

but unfortunately, this is not guaranteed to work due to unpredictability of the content of any padding bytes your struct objects might have in them.

The best course of action in this case might be to write a comparison function manually

inline bool is_same_number(const number *lhs, const number *rhs)
{
  return lhs->a == rhs->a && lhs->b == rhs->b && lhs->c == rhs->c;
}

and then use it in combination with compound literal feature

if (is_same_number(&foo, &(number) { 1, 2, 3 }))
  ...

Not sure you need a struct but either way just cast to unsigned char * and use a literal where 0x000000010002 would be the format of the literal representing 3 integers {0 1 2}.

To avoid issues with endianess just declare the integral as a value at runtime and then the representation will match the system endian.

You could also use a macro if run time definition was not allowed.

I wouldn't waste the memcpy.

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