simple c++ program adding 1

So I started programming a few days ago and have trouble with this simple C++ program. Can anyone tell me how to fix it (Output should be 1 instead of 0). Thanks in advance :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <iostream>

using namespace std;

int main ()
{
    int i;
    i = 0;

    if (int i = 0)
    {
        i++;
    }
    else 
    {

    }

    cout << i << endl;

    return 0;
    
}
Change
 
if(int i = 0)


To
if(i == 0)
Line 10 you are creating a new variable i that is only usable in the if/else block. The i you create at line 7 is never incremented.

You have two separate i variables because of local scoping.

https://www.learncpp.com/cpp-tutorial/introduction-to-local-scope/

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
   int i = 0;

   if (i == 0)
   {
      i++;
   }

   std::cout << i << '\n';
}
GIves me an error ;/

invalid '==' at end of declaration; did you mean '='?
if (int i == 0)
^~
=

There are two problems here:

1) You've created two variables called i:

One is at line 7, at the start the main function.

One is at line 10, in the if block. Inside the if block, this i hides the first one. So, inside the block, anything you do to i will be to this second variable.

However, once the block finishes, that second i is destroyed. Outside the block, the first i is used, and that never had its value changed, so it's still 0.

Solution: remove the int from line 10. That way, you're looking at the variable you declared at line 7 all the way through your program.

2) You've confused =, the assignment operator, with ==, the equality test operator. In line 10, you're not checking that the value of i is 0, you're setting it to 0.

The gotcha is that the expression (i = 0) evaluates to the value of i, which is 0. And in a boolean statement, 0 means false - so the if block won't be executed, and the else block will.

So, that's two things you need to change.

EDIT: Ninja'd by several people! That's what I get for writing a long post explaining things...
Last edited on
MikeyBoy wrote:
Ninja'd by several people! That's what I get for writing a long post explaining things...

You added the very much needed = vs. == issue, and how that affects Boolean logic. :)
Thank you guys so much! :)
You're welcome - hope it makes sense now.
Topic archived. No new replies allowed.