+ 2

Location of declaration

#include <iostream> using namespace std; int main() { int a,b; int x=a+b; cin>>a>>b; cout<<x; return 0; } I tried to add 2 numbers but the result was 8 no matter what numbers I give it but when I put int x=a+b after input of a and b it works. I believes that the compiler thinks x a+b before input nit after but why 8 ? #include <iostream> using namespace std; int main() { int a,b; cin>>a>>b; int x=a+b; cout<<x; return 0; }

4th Nov 2018, 1:37 PM
Odai
Odai - avatar
3 ответов
+ 2
If you use a variable before giving it a value it can be anything. If you change `int a,b;` to `int blah,a,b;` you will probably get a different number. The variable `a` sits somewhere in your computer's memory and whatever was written in that location before your main function was executed will be the value of `a`.
4th Nov 2018, 1:56 PM
Schindlabua
Schindlabua - avatar
+ 2
Kind of but which value that is, is unknown.
4th Nov 2018, 2:56 PM
Schindlabua
Schindlabua - avatar
+ 1
in other words there is default value for a and b
4th Nov 2018, 2:30 PM
Odai
Odai - avatar