How does this for loop work?

Discussion in 'C Programming' started by Circuits, Oct 8, 2020.

  1. Circuits

    Circuits

    Joined:
    Apr 14, 2020
    Messages:
    2
    Likes Received:
    0
    I was wondering if someone could help me understand what's happening here:

    Code (C):
        int set = 0;
        for (auto & info : m_guidancePlugin->jobGuidanceList())
        {
          set |= info.type;
        }
    Mainly this part:

    Code (C):
    set |= info.type
     
    Circuits, Oct 8, 2020
    #1
    1. Advertisements

  2. Circuits

    deathshadow

    Joined:
    May 26, 2019
    Messages:
    4
    Likes Received:
    0
    IT's hard to say without knowing what info.type is, or auto is... or m_guidancePlugin for that matter...

    But that line is a binary "or". So whatever info.type is it's likely some sort of use of binary flags.

    For example you might have something like:
    Code (Text):

    #define ALLOW_NONE  0x00
    #define ALLOW_READ  0x01
    #define ALLOW_WRITE 0x02
    #define ALLOW_EXEC  0x04
     
    Let's say you want users permissions to set the file permissions.

    Code (Text):

    int permission = user.isLoggedIn ? ALLOW_READ | ALLOW_NONE;
    if (user.isModerator) permission |= ALLOW_WRITE;
    if (user.isAdmin) permission |= ALLOW_EXEC | ALLOW_WRITE;
     
    If they're logged in it's at least 1, if they're a moderator it's 3, if they're an admin, it's 7.

    Since 0x01 | 0x02 | 0x04 == 0x07

    Just as ALLOW_READ | ALLOW_EXEC is 5.

    Most C operators can be used on assignment. *=, /=, +=, -=, |=, &=, even ~= is valid. In this case it's the same as saying:

    set = set | info.type
     
    deathshadow, Oct 9, 2020
    #2
    1. Advertisements

  3. Circuits

    Circuits

    Joined:
    Apr 14, 2020
    Messages:
    2
    Likes Received:
    0
    I think it would take a lot of time and code to explain all of that, but here is the definition for type:

    Code (Text):
    Guidance::Type type = Guidance::StraightAB;
    where Guidance::StraightAB = 2 and type is 4 bytes.
     
    Circuits, Oct 15, 2020
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.
Similar Threads
There are no similar threads yet.
Loading...