简体   繁体   中英

Bitwise operators in c++ and overloading

I have written some code to print the value of an integer raised to an integer power. Why does this code pause for input even after I have entered 2 integers?

#include<iostream>

int main(){
    int a, b;
    std::cin>>a>>b;
    std::cout<<std::endl<<a<<std::endl<<b<<std::endl;
    int c, d;
    c = a;
    d = 0;
    while(b){
        if(b&1)
            d += c;
        if(b>>1){
            b = b>>1;
            c *= c;
        }
    }

    std::cout<<d;
    return 0;
}

I suspected that the compiler misinterprets the bitwise operator as an overloaded operator, but even if I change the condition in the while loop to

if(b/2 > 0){
    b = b/2;
    c *= c;
}

it still doesn't work. I have no idea what is going on here. I've tried this code in the terminal, and some online IDEs, but the result is the same.

std::cin>>a>>b; is grouped as (std::cin>>a)>>b; so be assured that two integers are read.

Your problem is that the program loops if b is anything other than 0.

As noted, you never assign a 0 value to b, so the loop never ends. You can replace the if test with something that does the assignment.

if(b >>= 1)
    c *= c;

I prefer this to b = b >> 1 as it is more obvious you mean to assign, and don't mean to compare b == b >> 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM