I'm trying to set a bit at a given position but I keep getting an error can someone help with this?
This is my code:
int set_bit(unsigned long int *n, unsigned int index)
{
long unsigned int value;
value = n | (1 << index);
}
int main(void)
{
int n;
n = 1024;
set_bit(&n, 5);
printf("%lu\n", n);
n = 0;
set_bit(&n, 10);
printf("%lu\n", n);
n = 98;
set_bit(&n, 0);
printf("%lu\n", n);
return (0);
}
CodePudding user response:
- You should dereference the pointer
n
to get theunsigned long int
value. - You should use
lu
prefix to the literal1
to useunsigned long
instead ofint
to prevent overflow in the shift operation. - The return value of
set_bit
is not used and noreturn
statement is used, so the return type should bevoid
. stdio.h
should be included to useprintf()
.
Try this:
#include <stdio.h>
void set_bit(unsigned long int *n, unsigned int index)
{
*n = *n | (1lu << index);
}
int main(void)
{
int n;
n = 1024;
set_bit(&n, 5);
printf("%lu\n", n);
n = 0;
set_bit(&n, 10);
printf("%lu\n", n);
n = 98;
set_bit(&n, 0);
printf("%lu\n", n);
return (0);
}
CodePudding user response:
your set_bit function is expecting lu pointer (unsigned long int *n) while you are treating it in the function as a lu value (n | (1 << index)).
write it a bit differently - value= *n | (1 << index)