问题描述
我刚开始学习c + +,我遇到了一个小问题。在声明变量后,他们将值分配给它们。
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;
}
例如,变量s是1967866170。
For example variable s is 1967866170. Shouldn't they all be 0? What am I doing wrong?
推荐答案
未分配任何值的局部变量具有(也称为垃圾值,它是以前存储在该内存位置的值(在c和c ++中) )和访问未初始化的变量会导致未定义的行为。
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.
但 static
和全局变量的默认值为0
But static
and global variables have default value as 0
这篇关于变量在声明它们之后具有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!