+ 1

why did that display (0) even when i had not declare the b[9] variable?

#include <iostream> using namespace std; int main() { int b[7]; cin>>b[0]; cout << b[0] << endl; // Outputs 11 cin>>b[9]; cout<< b[9] << endl; // Outputs 70 return 0; } In the above program, I gave (5) and (b) as the input{content inside the braces as input} but it's output was : 5 0 so I dont know why did that happen? because i didn't declare the variable b[9]

21st Dec 2017, 9:37 AM
SHASHANK SINGH
SHASHANK SINGH - avatar
2 Answers
+ 2
You defined the variable b as an array of 7 integers. b[9] is not a separate variable. The compiler thinks b[9] is the 10th position in that array b, but it is an "illegal" position because beyond 7. You can try to assign and retrieve values from there, and it may work (depending on compiler) but that position in memory may also be modified by other parts of the code.
23rd Dec 2017, 7:28 AM
ifl
ifl - avatar
+ 1
b is a char, not a number so when cin tried to cast "b" as an integer, it stopped on the first character and returned 0
21st Dec 2017, 9:48 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar