-2

I'm new to C, and am trying to make sense of some code from NREL available here so that I may program a similar function in R. Here's the part of the code I cannot seem to figure out:

long S_solpos (struct posdata *pdat)
{

if ( pdat->function & L_DOY )
    doy2dom( pdat );     
}

In particular, what is the evaluation criteria asking in:

if ( pdat->function & L_DOY )

I understand that pdat is a is a pointer to the posdata structure, and from the header file I know that that "function" is a variable in the posdata structure which contains various integer codes:

struct posdata
{
int   function;

and that L_DOY can be one such function:

/*Define the function codes*/
#define L_DOY    0x0001
#define L_GEOM   0x0002
#define L_ZENETR 0x0004

I would assume that the if statement is checking whether the function variable within pdat corresponds to the code for L_DOY. However, I am still very new to C, and have been unable to find any examples or explanations that utilize the ampersand in an if statement like this.

Thanks in advance for any help.

arharris
  • 13
  • 4
  • 4
    https://en.wikipedia.org/wiki/Bitwise_operations_in_C#Bitwise_AND_.22.26.22 – Adrian Jun 22 '16 at 22:42
  • A single ampersand is a bitwise AND operator in Boolean Algebra, often used as a bit-mask. If you are unfamiliar with these concepts see google or wikipedia to explain them. – Arif Burhan Jun 22 '16 at 22:44
  • 2
    Possible duplicate of [what is use of &(AND) operator in C language?](http://stackoverflow.com/questions/24836647/what-is-use-of-and-operator-in-c-language) – Michael Gaskill Jun 22 '16 at 22:50

1 Answers1

2

It means bitwise-and. The value it's testing is a set of bit flags that can have one or more set. It's checking whether the L_DOY flag specifically is set, because bitwise-and keeps bits that appear in both operands, so 0b0101 & 0b0011 would produce 0b0001 (the only bit set in both operands). Since L_DOY is only a single bit, the low bit, it's checking if that bit is set in function; it doesn't care if other bits are set, or not.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271