Variables have values ​​after declaring them

I am just starting to learn C ++ and I am having a little problem. After declaring variables, they assign a value to them.

#include <iostream>
#include <fstream>
using namespace std;

ifstream d ("d.txt");
ofstream r ("r.txt");

int plotas (int a, int b);

int main()
{
    int p,
        a,
        n,
        x1,
        x2,
        y1,
        y2,
        s,
        s1;
    d >> p >> a;
    d >> n;
    for(int i =0; i < n; i++){
        d >> x1 >> y1 >> x2 >> y2;
        s+= plotas((x2-x1), (y2-y1));
    }
    s1= plotas(p, a)- s;
    cout << s1;
}
int plotas (int a, int b){
    return a*b;
}

      

For example, s is 1967866170. Shouldn't they be 0? What am I doing wrong?

0


source to share


4 answers


Local variables that are not assigned any value have what is called an Undefined Value (also known as Garbage Value, this is a value that was previously stored in that memory location (in c and C ++)) and accessing uninitialized variables results in Undefined Behavior.

If you don't assign a value to them, they will have a garbage value.



But static

also global variables have default value as 0

+4


source


http://en.cppreference.com/w/cpp/language/default_initialization

The default initialization is done in three situations:

1) when a variable with automatic, static or streaming storage is declared without an initializer .

2) when an object with dynamic storage duration is created by a new expression without an initializer, or when an object is created by a new expression with an initializer consisting of an empty pair of parentheses (before C ++ 03).

3) when the base class or non-static data member is not mentioned in the list constructor initializer and the constructor is called.




Default initialization effects:

If T is a non-POD class (prior to C ++ 11), constructors are examined and overloaded against an empty argument list. The selected constructor (which is one of the default constructors) is called to provide an initial value for the new object.

If T is an array type, each element of the array is initialized by default.

Otherwise, nothing is done: objects with automatic storage duration (and their sub-objects) are initialized to undefined value.

+3


source


Accessing uninitialized variables will result in undefined behavior . Also see this answer .

You need to initialize 's' before doing the addition assignment s + = plotas ((x2-x1), (y2-y1)).

0


source


Just initialize the variables so they don't take on any value for garbage:

int p=0, a=0,n=0,x1=0,x2=0,y1=0,y2=0,s=0,s1=0;

      

You can also initialize them with anything int

other than 0

as your code wants.

0


source







All Articles