1

I have a program in C++. I did something like this:

#include <iostream>
int main() {
unsigned x,cifra,cifraOld;
std::cout<<cifra;
}

For some reason, the output was 8. Can someone tell me if 8 is the default value for unsigned variable? If not, why is this happening to me?

Changing the line to unsigned x,cifra=0,cifraOld; will output 0.

ezluci
  • 61
  • 1
  • 6

1 Answers1

4

This declaration:

unsigned cifra;

initializes cifra to an indeterminate value.

Reading from an indeterminate value, e.g. like this:

std::cout<<cifra;

invokes undefined behavior (UB).

Printing 8 is entirely possible for a program with UB. It could print 0, or 42, or "hello world" for that matter. And in fact, the program could print not just any value, but as far as the language is concerned, anything could happen. In practice, you'll usually get some numeric value (which is a value that just happened to be at the memory location that was read from). If you're lucky the program will segfault, and alert you to the UB before it causes a serious issue.

cigien
  • 57,834
  • 11
  • 73
  • 112