3

I am trying to check whether this equal to zero as

//Address already malloc

void MyCheck (void *Address){

    if ( (long)Address & (~(sizeof(long)-1)) != 0 ){
           printf("Invalid");
    }

}

When try to compile it give me:

Error:  suggest parentheses around comparison in operand 
         of '&' [-Werror=parentheses]
ldav1s
  • 15,885
  • 2
  • 53
  • 56
Vineet1982
  • 7,730
  • 4
  • 32
  • 67

4 Answers4

10

!= has higher precedence than & , so your code is really doing the same as :

if ((long)Address &  ( (~(sizeof(long)-1)) != 0 ) )
                     ^                          ^

gcc suggests this might be an error, which it probably is. You'd want:

if ( ( (long)Address &  (~(sizeof(long)-1)) ) != 0 )
     ^                                      ^
nos
  • 223,662
  • 58
  • 417
  • 506
  • @haccks Um. that chart has `!=` *above* `&` , unless you're suggesting the chart is in low-to-high order, which it isn't. – WhozCraig Feb 20 '14 at 21:36
  • @haccks C operators in order of precedence (highest to lowest). – Vineet1982 Feb 20 '14 at 21:38
  • @WhozCraig; My bad. I looked over here `= += -= *= /= %= &= ^= |= <<= >>=` and thought `|=` to be `!=` :) – haccks Feb 20 '14 at 21:38
  • In case anyone cares : [Near-Duplicate Question Here](http://stackoverflow.com/questions/4685072/c-operator-precedence-bitwise-lower-than) – WhozCraig Feb 20 '14 at 21:39
2

Place a braces around (long)Address & (~(sizeof(long)-1)) in if statement.

if ( ( (long)Address & (~(sizeof(long)-1)) ) != 0 ){
haccks
  • 104,019
  • 25
  • 176
  • 264
2

!= is of a higher level of precedence than &, so what you're actually saying is:

if ((long)Address & ((~(sizeof(long)-1)) != 0)){
       printf("Invalid");
}

Instead, put parentheses around the first part:

if (((long)Address & (~(sizeof(long)-1))) != 0){
       printf("Invalid");
}

However, having a lot of background in TI-Basic and C, I would personally leave out the != 0 part:

if ((long)Address & (~(sizeof(long)-1))){
       printf("Invalid");
}
bb94
  • 1,294
  • 1
  • 11
  • 24
  • Your answer is also correct but for validation i need !=0 – Vineet1982 Feb 20 '14 at 21:34
  • @Vineet1982 Just in case someday 0 != 0, you want to be absolutely sure ? The last snippet in this is defined to do exactly what the second does. If by validate you mean appeasing some code reviewer that doesn't know C from A, B, or ice-cream, ugh, but ok. – WhozCraig Feb 20 '14 at 21:42
1

Although other answers have addressed the compiler error, you could sidestep the problem with:

if ((uintptr_t) Address % sizeof(long)) …

(To get uintptr_t, include <stdint.h>. And, if you are using C 2011, you might want to replace sizeof(long) with _Alignof(long).)

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312