-1

This is a function to check a number for a power of two. Although the compiler does not print anything, it's also not showing any errors. Please let me know if the logic is correct or not.

Here is my code:

#include <bits/stdc++.h>
using namespace std;

bool isPowerofTwo(long long n)
{

   // Your code here
    
    for (int i = 1; i <=n; i<<1)
    {
    
       if(i==n){
          return true;
       }

    }
    
   return false;
}

int main()
{

   cout << isPowerofTwo(2);

   return 0;
}
Ollie
  • 279
  • 5
  • 15
  • Please don't tag your question as both C and C++. Those are two different languages. – Brian Apr 04 '21 at 18:57
  • You may be interested in reading [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). Also potentially useful, but not important here: [C++ bool returns 0 1 instead of true false](https://stackoverflow.com/questions/8261674/c-bool-returns-0-1-instead-of-true-false) – Brian Apr 04 '21 at 18:58
  • 2
    Try stepping through the program in a debugger. Note in particular that your loop never terminates. – Raymond Chen Apr 04 '21 at 18:59
  • 1
    `i<<1` does not change the variable i. – S.M. Apr 04 '21 at 19:00
  • 1
    [My compiler warns about this code.](https://gcc.godbolt.org/z/rn7aszTnc) – chris Apr 04 '21 at 19:13
  • MSVC++, g++, and clang [all complain about this code](https://godbolt.org/z/f5jhhbbhq). – Drew Dormann Apr 04 '21 at 19:27

1 Answers1

2

The expression i<<1 in the third statement (the "iteration expression") of your for loop doesn't actually do anything (that is, it doesn't modify the value of i). You need, instead, i<<=1 (or, in 'long form', i = i << 1).

Also, please read: Why should I not #include <bits/stdc++.h>?. In your code, the only standard header you need is #include <iostream>. Another good post to read is: Why is "using namespace std;" considered bad practice?.

Adrian Mole
  • 30,672
  • 69
  • 32
  • 52