1

I was trying to learn C++ on my own, and there's a weird result from my first testing with the code in VSCode.

My testing code is as below:

#include <iostream>
using namespace std;

int main()
{
    int x, y, sum = 0;

    for (int x = 0; x < 5; x++)
    {
        y += 2;
        sum = x + y;
        cout << "The sum is = " << sum << "\n";

        if (x == 5)
        {
            break;
            return 0;
        }
    }
}

Which is supposed to give out the results as:

Above is the correct result which I tested on other online compilers. While in VSCode, I get the below result instead in the terminal after I run the code:

Is it just me or VSCode is not suitable or are there things I should configure/set up for C++? Thanks

Dnis
  • 31
  • 3
  • `y += 2;` what is the value of `y` before this line is executed, and what is it afterwards? Spoiler: `y` is uninitialized, incrementing it is undefined behavior – 463035818_is_not_an_ai May 23 '23 at 07:05
  • common rule of thumb is to always initialize variables as soon as you declare it ( never declare a variable without initializing it(. And this is much easier to follow if you also stick to another rule: Declare only one variable per line. – 463035818_is_not_an_ai May 23 '23 at 07:06
  • `int x, y, sum = 0;` is the same as `int x; int y; int sum = 0;` it should be `int y =0; sum = 0;` (you are not using `x`, there is a second `x` in the loop, but its a distinct separate variable) – 463035818_is_not_an_ai May 23 '23 at 07:08
  • First of all, VSC has nothing to do with the result, as it's just a text editor. Only your compiler choice matters here. Second, you should enable compiler warnings (assuming the compiler is GCC, that would be something like `-std=c++20 -Wall -Wextra -pedantic-errors`). The compiler should've warned you about the uninitialized variable. – HolyBlackCat May 23 '23 at 07:08
  • Good example of why it's not very *practical* to learn C++ on your own. Buy a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282). You will find as you continue learning C++ that when something doesn't work as expected, it is almost always your error or lack of understanding that is to blame, rather than the tools you are using. C++ is complex and for most beginners non-intuitive. – john May 23 '23 at 07:33
  • [Results using clang](https://godbolt.org/z/TbEPzvqs6). – PaulMcKenzie May 23 '23 at 07:37

1 Answers1

2

The problem here is that you are not initialising the value of y to zero in your code.

int x,y=0,sum=0;

This should solve your problem.