-3

I'm new to C++ and is trying to learn the concept of pointer. The example below is from C++ Primer 5th Edition. I have a few questions regarding to the statement:

1) What happens if pi3 is defined OUTSIDE a block?

2) What is a block in C++?

3) What kind of behavior does the uninitialized pi3 exhibit?

int *pi3; // if pi3 is defined inside a block, pi3 is uninitialized
halfer
  • 18,701
  • 13
  • 79
  • 158
Thor
  • 8,608
  • 10
  • 43
  • 113
  • 1
    Useful reading: http://stackoverflow.com/questions/5727/what-are-the-barriers-to-understanding-pointers-and-what-can-be-done-to-overcome and http://stackoverflow.com/questions/22146094/why-should-i-use-a-pointer-rather-than-the-object-itself – Tas Jan 06 '16 at 23:40
  • 1
    (1) It becomes global. (2) A block starts with `{` and ends with `}`. (3) Undefined behaviour. – user207421 Jan 06 '16 at 23:45
  • 1
    If `pi3` is not accessed, it may be eliminated, dropped, as a compiler optimization; regardless of where it is defined. – Thomas Matthews Jan 06 '16 at 23:47
  • One question per question please – Lightness Races in Orbit Jan 06 '16 at 23:49

1 Answers1

1

If you define a variable (like pi3) outside any blocks, it will be a global variable.

In C++, a block delimits a static scope. Any variables declared in the block are available only within that block; they will not be available outside of the block.

An uninitialized variable will have an indeterminate value -- it could be anything! In the case of a pointer, it could point anywhere...

Stereotypically, the data in an uninitialized variable is "whatever data happened to be written to that space beforehand, because we were too lazy to wipe it." It turns out there is a reason for being that lazy: if you define a large local variable (such as long array), automatically wiping the data could be a real performance hit. So, the default is to leave it uninitialized.

comingstorm
  • 23,012
  • 2
  • 38
  • 64