Solved: What's the use of "?" and ":0" in this piece of code from the sleep.h library?

Go To Last Post
4 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I was working on a project and wanted to see how the sleep.h file was made for trying to understeand how to use some "define" related stuff... and this next piece of code got me really confused:

 

#define set_sleep_mode(mode) \
    do { \
        MCUCR = ((MCUCR & ~_BV(SM1)) | ((mode) == SLEEP_MODE_PWR_DOWN || (mode) == SLEEP_MODE_PWR_SAVE ? _BV(SM1) : 0)); \
        EMCUCR = ((EMCUCR & ~_BV(SM0)) | ((mode) == SLEEP_MODE_PWR_SAVE ? _BV(SM0) : 0)); \
    } while(0)

My question is... what is the use of the "?" character in the code? and why finishing the 3rd line with a ": 0"?... clearly those are some code-related things I never learned... anybody can explain please?

Victor

Last Edited: Mon. May 28, 2018 - 12:50 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Vleroylr wrote:
My question is... what is the use of the "?" character in the code? and why finishing the 3rd line with a ": 0"?
Google for "ternary operator".

Stefan Ernst

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

This is the C ternary operator:

a ? b: c;

I a is true (different from zero), this expression takes the value b; if false (zero), it takes the value c.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks for the replies!, it #definatly answered my question, thanks a lot!

Victor