0

Im just starting to learn c++ and I've run into a little problem. After declaring variables they have value assigned 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 variable s is 1967866170. Shouldn't they all be 0? What am I doing wrong?

PoVa
  • 995
  • 9
  • 24

4 Answers4

4

Local variables that are not assigned any values have what is called Indeterminate Value ( also known as Garbage Value, it is the value that was previously stored in that memory location ( in c and c++) ) and accessing uninitialized variables leads to Undefined Behavior.

If you do not assign them a value, they will be having the garbage value.

But static and global variables have default value as 0

Community
  • 1
  • 1
Arun A S
  • 6,421
  • 4
  • 29
  • 43
3

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

Default initialization is performed in three situations:

1) when a variable with automatic, static, or thread-local storage duration is declared with no initializer.

2) when an object with dynamic storage duration is created by a new-expression with no initializer or when an object is created by a new-expression with the initializer consisting of an empty pair of parentheses (until C++03).

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


The effects of default initialization are:

If T is a non-POD (until C++11) class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object.

If T is an array type, every element of the array is default-initialized.

Otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.

user3528438
  • 2,737
  • 2
  • 23
  • 42
0

Accessing uninitialized variables will lead to undefined behavior. Also, see this answer.

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

Community
  • 1
  • 1
0

Simply initialise the variables to prevent them from assuming any garbage value:

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

You can also initialise them to any int other than 0 as your code desires.

Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43