+ 1

Why does the computer output these array elements?

#include <iostream> using namespace std; int main() { int b[100] ; cout << b[0] << endl; // CONSISTENTLY returns a constant 0 cout << b[96] << endl; // returns an unpredictable, changing integer cout << b[97] << endl; //returns an unpredictable, changing integer return 0; } ============== Why does the computer generate these outputs for undefined elements? One might expect all of them to be zero... ============== When ' int b[100]; ' is placed outside of main(){} the output seems to be always zero. Why is this the case?

4th Aug 2020, 8:45 PM
Solus
Solus - avatar
5 odpowiedzi
+ 3
Solus When you place before main, then it becomes global variables. Global and static variables are set to default value 0. But you should assign values to local variable before you use it.. And the values you taking is also garbage value.. if run same code after again ,n again or some time or few days later, you *may* not get same result.. And try run the same code in other compilers, then you may get different results..
4th Aug 2020, 9:27 PM
Jayakrishna 🇮🇳
+ 2
Those are all garbage values... You are not initialized any values so it returns a garbage value just... those are values previously assigned by any other programs on that locations..
4th Aug 2020, 8:52 PM
Jayakrishna 🇮🇳
+ 1
When using a uninitialized variable. You allocated a memory spot which has been used before. Sometimes there is a number in it, sometimes there isn't. It is unpredictable and unconsitant and can cause hard to debug bugs. Please always initialize your variables, you are looking at garbage (old variable values, or part of old variable value that have been used)
4th Aug 2020, 8:52 PM
sneeze
sneeze - avatar
+ 1
When ' int b[100]; ' is placed outside of main(){} the output seems to be always zero. Why is this the case?
4th Aug 2020, 9:02 PM
Solus
Solus - avatar
0
Jayakrishna🇮🇳 sneeze Then how come b[99], for instance, consistently generates 0?
4th Aug 2020, 8:56 PM
Solus
Solus - avatar