-2

I'm trying to write simple program using c to compute the intersection between two strings using Bitwise AND operator Like :

        char x[]="abcdefghijklmnopqrstuvwxyz";
        char y[]="abcdefghijklmnopqrstuvwxyz";

        int i,sum=0;
        const int size = 26;

        for(i=0;i<size;i++)
        {   
            if(x[i]&y[i]==y[i]){
                printf("%c",y[i]);
                sum++;
            }
        }

        printf("\n%d\n",sum);

After executing code i found the result :

acegikmoqsuw
13

what's the problem with my code or what's the reason for that ?

Mohamed Slama
  • 189
  • 1
  • 3
  • 17

3 Answers3

4

You should take care of operand precedence in the if:

    char x[]="abcdefghijklmnopqrstuvwxyz";
    char y[]="abcdefghijklmnopqrstuvwxyz";

    int i,sum=0;
    const int size = 26;

    for(i=0;i<size;i++)
    {
        if((x[i] & y[i]) == y[i])
        {
            printf("%c",y[i]);
            sum++;
        }
    }

    printf("\n%d\n",sum);
emi
  • 2,786
  • 1
  • 16
  • 24
  • It might be an example of a more complicated thing, like, for example, where `x != y`. – emi Dec 06 '15 at 21:50
  • yes you are write thanks but why i should write like that i always write this expression with no error – Mohamed Slama Dec 06 '15 at 21:51
  • 1
    http://stackoverflow.com/questions/4685072/operator-precedence-bitwise-lower-than The && and || operators were added later for their "short-circuiting" behavior. Dennis Ritchie admits in retrospect that the precedence of the bitwise operators should have been changed when the logical operators were added. But with several hundred kilobytes of C source code in existence at that point and an installed base of three computers, Dennis thought it would be too big of a change in the C language... – emi Dec 06 '15 at 21:53
1

Your code isn't strictly correct; if every x[i] were 0xff then it'd think that every character matched. All you're going to detect is anywhere that the relevant x has a 0 that the relevant y does not.

If the requirement is to use &, for whatever academic purpose, then run the test in both directions:

if( (x[i]&y[i])==y[i] && (x[i]&y[i])==x[i] )

i.e. if there are no bits set in y that are not also set in x and there are no bits set in x that are not also set in y then the two must have the same bit pattern.

Though, obviously:

if( x[i]==y[i] )

... is the intended means of testing for equality in C.

Tommy
  • 99,986
  • 12
  • 185
  • 204
0

Your problem lies in the evaluation of the if statement

if(x[i]&y[i]==y[i])

the == operator has greater precedence than the & operator.
https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
Try replacing it with this:

if( (x[i] & y[1]) == y[1] )