0

I'm writing simple function which returns maskable array of zeros and ones to array of numbers.

If number is a power of two maskable index will be one if not then zero.

It works fine without passing my simple function isPower() , but when I do pass it. weird things happen.

I want my code works with

if(isPower(nums[i])) 

Without or condition

#include<stdio.h>

int *isPowerOf2(int num, int*nums,int *result);
int isPower(int num);
int main(void)
{
int array[]= {1,2,2,4,4,3,4,3,3,4,4,4,4,4};
int size=0;
int *result=NULL;
result=isPowerOf2(14,array,&size);

for(int i=0; i<size; i++)
{
    printf("%i : %i\n",array[i],result[i]);
}
free(result);
printf("%i",size);
return 0 ;
}

int *isPowerOf2(int num, int*nums,int *result_num)
{
int *result=(int *)malloc(num*sizeof(int));

*result_num=num;
for(int i=0; i<num; ++i)
{
    if(isPower(nums[i])||!(nums[i]&nums[i]-1)) //this won't work  but when I use !(nums[i]&nums[i]-1) it works fine
    {
        result[i]=1;
    }
    else
    {
        result[i]=0;
    }

}
return result;
}

 int isPower(int var)
 {
 return ((var)&(var-1)==0)?1:0;
 }
8
  • 1
    You need to learn basics of C language and OR operator. Second operand of OR statement is NOT executed if first one evaluates to non-zero value. Commented Mar 22, 2018 at 8:42
  • I think you did not get my point I added second operand because without it won't work. I did add it to clarify my question, but I want code work without it. it supposed not be there. Commented Mar 22, 2018 at 8:45
  • 1
    You second operand nums[i]&nums[i]-1. Do you know the sequence of execution here? Commented Mar 22, 2018 at 8:47
  • 1
    Focus on isPower function: return ((var)&(var-1)==0)?1:0; should be return (((var)&(var-1))==0)?1:0; Commented Mar 22, 2018 at 8:50
  • 2
    Also, clean it up. If I can't immediately identify by eye the start/end of functions, I close-voe as 'Unclear' and move on to the next question. Commented Mar 22, 2018 at 9:00

2 Answers 2

3

At times like this it pays to check what you're actually computing:

#include<stdio.h>

int main() {
    printf("%d %d\n",!(7&6),((7&6==0) ? 1 : 0)); //Not a power of 2
    printf("%d %d\n",!(8&7),((8&7==0) ? 1 : 0)); //Power of 2
    return 0;
}

Returns:

0 0
1 0

If you think about it a bit, should make sense. Or does it? Operator precedence is killing you here. Why would the bottom right be 0?

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, hope I give more attention next time :)
1

Befare that (1 & 2) is a bitwise operand while (1 && 2) is the logical operand.

So to be clear: (1 & 2) == 0 is something completely different than !(1 & 2).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.