Advertisement

04.30.2008 at 04:46PM PDT, ID: 23367298
[x]
Attachment Details

What exactly is the value of the expression Char1 & Char2 ?

Asked by stevefromc in C Programming Language

Suppose I have the following
(I've chagned the application from my company's domain (Healhtcare) to the good old days of being a student for proprietary reasons :) )

#define  MATH 1
#define  ECONOMICS 2
#define PSYCHOLOGY 4
#define  SOCIOLOGY 8
which are possible values of a bitmap that contains course(s) of study at a university.
That is, with the STUDENT structure you'd have
char Majors; // a student can have 2 majors so for an econ/psych major, this would be 4+2=6

And I might have a local variable
char OneMajor;

I know that I can check if a student is taking major course OneMajor by writing:
if (student.Major & OneMajor)
  printf("Matched!\n");
e.g. in the above example, if OneMajor = 4 (PSYCHOLOGY), and student.Major = 6, the IF would pass.

Now today I found the following IF in some undocumented code:

if ( (student.Major & OneMajor) == OneMajor)
   printf("Mached!\n");

My questoin is, are these two IF's the same? I ran a few tests, and based on a VERY FEW cases,
it seems that if the"&" succeeds, the value of (student.Major & OneMajor) is Major.

If indeed that's correct, then can I safely say that

if (student.Major & OneMajor)
and
if ( (student.Major & OneMajor) == OneMajor)

will accomplish the same thing for me?

Thanks,
Steve
Start Free Trial
 
 
Loading Advertisement...
 
[+][-]04.30.2008 at 04:57PM PDT, ID: 21475527

View this solution now by starting your 7-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zone: C Programming Language
Sign Up Now!
Solution Provided By: hielo
Participating Experts: 3
Solution Grade: A
 
 
[+][-]04.30.2008 at 04:58PM PDT, ID: 21475528

Assisted solutions are selected by the member who asked the question as a comment that contributed to their question's solution.

Start your 7-day free trial to view this Assisted Solution or ask the Experts your question.

 
 
Loading Advertisement...
20080716-EE-VQP-32 / EE_QW_2_20070628