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;
}
Clanguage andORoperator. Second operand of OR statement is NOT executed if first one evaluates to non-zero value.nums[i]&nums[i]-1. Do you know the sequence of execution here?isPowerfunction:return ((var)&(var-1)==0)?1:0;should bereturn (((var)&(var-1))==0)?1:0;