0

If we simply declare an integer variable in C++ , and print it why am I getting 0 instead of garbage value every time. How to declare each element of array as 1 without using loop.

#include<iostream>
using namespace std;
int main()
{
    int a;
    cout<<a;    // displays zero
}
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 5
    What garbage value do you expect? Why 0 is not a garbage value for you? – Daniel Langr Jan 09 '23 at 11:37
  • 2
    Why is `0` not a "garbage value"? `a` is uninitilised, there is no guarantee that it will be non-zero or that your program won't just crash – Alan Birtles Jan 09 '23 at 11:37
  • The value of an uninitialized variable is undefined. It is usually "garbage" (i.e. apparently random), but there is no guarantee. It depends on the compiler and more low-level details. – matteo_c Jan 09 '23 at 11:38
  • 1. Consider yourself (un)lucky? Them's the breaks of undefined behavior. 2. You don't (intrinsics notwithstanding). – WhozCraig Jan 09 '23 at 11:38
  • 1
    If you don't give a (scalar) variable a value, then its value is not "garbage". It is _indeterminate_, which means exactly what the word says, nothing more. Reading an indeterminate value in itself causes undefined behavior. – user17732522 Jan 09 '23 at 11:39
  • Are you running a debug build? – Pepijn Kramer Jan 09 '23 at 11:50
  • The gcc gives warning ": warning: 'a' is used uninitialized [-Wuninitialized]" that means undefined behavior and undefined behavior means that it may display "widehole" or 0 or format your hard drive. Be happy you got 0. – Öö Tiib Jan 09 '23 at 11:55
  • Reading an uninitialized scalar value is Undefined Behaviour. Therefore you should have no expectations. https://en.cppreference.com/w/cpp/language/ub – Richard Critten Jan 09 '23 at 12:17

0 Answers0