0

I'm new to coding and I am trying to complete this assignment, but I can't get it to work:

Write and use a function that takes a mask as an argument and returns a structure.

Here is what I've done so far. Can someone help me understand what I'm doing wrong?

typedef enum {
    fast = 1,
    slow = 2,
    strong = 4,
    smart = 8,
    agile = 16,
}Skills;

typedef struct _Team {
int ranking;
char name;
} Team;

Team Alabama;

Team USC;

Team _function (Skills skills);
Team _function (Skills skills) {
    if (skills == (fast | smart)) {
        return Alabama; }
    if (skills == (fast | agile))
        return USC;
    else
        return nil;

}
Mat
  • 202,337
  • 40
  • 393
  • 406
  • Please explain what "can't get it to work" means exactly. What are your expected results, what are your actual results, and what are your thoughts about the difference? – jscs Sep 04 '12 at 02:04
  • 1
    And return `NULL` as an empty struct instead of `nil`. – Mazyod Sep 04 '12 at 02:21

1 Answers1

3

When you have mask-based enums, you check whether that enum is satisfied or not using the bit-wise AND operator &.

So, if you want to check if the skills are fast AND smart, do it like so:

if ((skills & fast) && (skills & smart)) {
    // this team has the brains and speed.. possible other stuff
}

Alternatively, in this situation, the XOR operator would also be a good candidate:

if (skills ^ (fast | smart) == 0) {
    // this team has ONLY the brains and speed.
}

Last Note:

Define the enums like this, much easier:

typedef enum {
    fast   = 1 << 0,
    slow   = 1 << 1,
    strong = 1 << 2,
    smart  = 1 << 3,
    agile  = 1 << 4,
} Skills;

EDIT:

OK, since this is an assignment, let me go through some trouble explaining how this works:

As am sure you know, your enums look something like this (Binary):

(00001)
(00010)
...
(10000)

Now, using the bit-wise OR operator |, you were able to merge two skills together:

   00001
OR 01000
   _____
   01001

Then, we can check if that new multi-skill enum has some specific skill using &:

    01001
AND 01000
    _____
    01000 != 0 (aka true)

To go to a more advance level, we use XOR, which by definition, sets the resulting bit to 0 if the two bits are equal:

    01001
XOR 01000
    _____
    00001 != 0 (aka true)

    01001
XOR 01001
    _____
    00000 == 0 (aka false)
Mazyod
  • 22,319
  • 10
  • 92
  • 157
  • 1
    It should also be mentioned that `nil` is not the correct return type to indicate "no structure". – jscs Sep 04 '12 at 02:02