Question

I'm writing a simple function in C, that returns a number of "1" in byte (bit by bit). Here is my code, the compiler tells: "expected expression before "=" token" in line where "for" starts.

#include <stdio.h>
#include <stdlib.h>

int return_num_of_1(unsigned char u);

int main()
{
    printf("Hello world!\n");
    return 0;
    return_num_of_1(1);
}


int return_num_of_1(unsigned char u)
{

    int counter;

    for (counter = 0; u; u << = 1)
    {
        if(u & 1) counter++;
    }

    return counter;
}
Was it helpful?

Solution

    for (counter = 0; u; u << = 1)

The compilation problem is here. You should be using operator <<= without spaces. If you put a space in-between, the compiler reads that as two separate operators: '<<' and '='.

You got a couple of other problems there as well, removing the space fixes the compilation.

OTHER TIPS

The space before the = is wrong, if you mean to use the bit shift left assign operator.

for (counter = 0; u; u << = 1) should be for (counter = 0; u; u <<= 1)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top