Student
Student

Reputation: 55

Syntax error in c with pow()

Cant figure out the syntax error I'm experiencing, I have the right headers so no idea

int get_block_size(int num) {
    int i= 0;

    for (i=0; num < pow(2.0,double(i)); ++i);

    return int(pow(2.0,double(i)));
}

The error I am getting

sidhuh@ius:~ $ gcc -o b buddy.c
buddy.c: In function `get_block_size':
buddy.c:24: error: syntax error before "double"
buddy.c:24: error: syntax error before ')' token

Upvotes: 1

Views: 189

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Your cast of i to double is incorrect: in C, you put the type in parentheses, like this:

for (i=0; num < pow(2, (double)i); ++i)
    ;
return (int)(pow(2,(double)i));

This should fix the syntax error. However, this is not the most efficient - you can get a power of two by shifting 1 left, so instead of writing

(int)pow(2, i)

you can write

1 << i;

This works for the same reason that you can obtain k-th power of ten in the decimal system by writing k zeros after 1.

Note: it looks like you are trying to round the number up to the nearest larder power of two. There is a "bit twiddling hack" that helps you do it with fewer operations and without the loop. Follow the description here.

unsigned int v; // compute the next highest power of 2 of 32-bit v
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;

Upvotes: 5

RobP
RobP

Reputation: 9522

int is a type, not a function, so I don't think the compiler likes int(... did you mean a typecast like

(int) pow(2.0, (double) i) 

maybe? That raises other error conditions, but it is at least syntactically correct.

Upvotes: 1

Related Questions