Why I am getting garbage(unwanted) output here?

不想你离开。 提交于 2019-12-20 04:25:18

问题


Whenever I am writing this following code, I am getting garbage(unexpected) output in some online compiler, but if I use code block then getting satisfied output. So my question is why I am getting this type of output?

for example, if I input

5 7
+ 5
- 10
- 20
+ 40
- 20

then I am getting

22 1

in the code block. But in the online compiler, it's something else.

#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
    int have, n, i;
    int kid=0;

    cin>>n>>have;

    int line[n];

    for(i=0;i<n;i++)
    {
        cin>>line[i];

        if(line[i]>=0)
            have+=line[i];
        else
        {
            if(have>=abs(line[i]))
                have+=line[i];
            else
                kid++;
        }
    }

    cout<<have<<" "<<kid<<endl;

}

回答1:


The main problem I can see in your code is this:

int line[n];

This is known as a VLA (Variable Length Array) and it is not supported in C++. It is valid in C. Most compilers still allow this behaviour due to the fact that C++ is based on C, but it is not valid C++ code. In a previous question, I found out that clang supports designated initializers, when gcc and vc++ did not. The reason is because some compilers like clang, support c99-extensions by default. My point is that just because the code compiles, it doesn't mean it's always right.

If you compile with the -pedantic argument, you will see that the compiler is warning you about this being a C99 feature. Have a look at the rextester example here. From the comments below, using -pedantic-errors in the compiler flags, will prompt an error.

If you know the size of the array before run-time, then you should use a static array int line[4];, but if you don't then you need to use a dynamic array. std::vector is essentially a dynamic array that also handles memory for you. It's easy to use and very efficient. std::vector<int> line;

You can read more about the vector container here: http://www.cplusplus.com/reference/vector/vector/

Btw, I tried your code in rextester, ideone and repl.it and I got the same results: 22 1. I think what you are witnessing it undefined behaviour.

Also, you can qualify int n with constexpr and it'll be fine.

constexr int n = 200;
int line[n]; //now it's ok.

But this again means that you know the size of the array at compile time.



来源:https://stackoverflow.com/questions/54673114/why-i-am-getting-garbageunwanted-output-here

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!