4

Would like to know in C++ what the value of unassigned integer in an int[] usually is.

Example

int arr[5];
arr[1]=2;
arr[3]=4;
for(int i=0;i<5;i++)
{
  cout <<arr[i] <<endl;
}

it print

-858993460
2
-858993460
4
-858993460

we know that the array will be {?,2,?,4,?} ,where ? is unknown.

What will the "?" be usually?

When I tested , I always got negative value. Can I assume in C++ unassigned element in the integer array is always less than or equal to zero?

Correct me if I'm wrong. When I study in Java unassigned element in array will produce null.

Werner Henze
  • 16,404
  • 12
  • 44
  • 69
V_Stack
  • 147
  • 2
  • 7
  • 15
  • 7
    You cannot assume anything - it's undefined behavior and you shouldn't rely on it. – Nbr44 Jul 24 '13 at 08:16
  • is there anyway to make int arr[5] = {}; producing sets of -1 or other value rather than just zero? – V_Stack Jul 24 '13 at 08:42
  • `int arr[5]; std::fill(arr, arr + 5, -1);` – Cody Gray - on strike Jul 24 '13 at 08:44
  • 1
    @YuvinNg, http://stackoverflow.com/questions/17828567/unassigned-value-in-the-int/17828581?noredirect=1#comment26020547_17828594. Alternatively, use something like `std::vector` and pass it into the constructor. – chris Jul 24 '13 at 08:54
  • There is no default initialization in c/c++. Per definition all unassigned values are undefined, i.e. may contain random values. Often they are assigned with special values to mark it as "unassigned" like 0xcccccccc (in your case). – bkausbk Jul 24 '13 at 09:34

6 Answers6

8

Formally, in most cases the very attempt to read an uninitialized value results in undefined behavior. So, formally the question about the actual value is rather moot: you are not allowed to even look at that value directly.

Practically, uninitialized values in C and C++ are unpredictable. On top of that they are not supposed to be stable, meaning that reading the same uninitialized value several times is not guaranteed to read the same value.

If you need a pre-initialized local array, declare it with an explicit initializer

int arr[5] = {};

The above is guaranteed to fill the array with integer zeros.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • 2
    That's very interesting, especially regarding the instability part: can you provide some documentation about that? – Antonio Jul 24 '13 at 08:23
  • all right, because right now im trying to create an int array let say of the size 100 and randomly insert postive integer into any position in the array. If the array is not full. how could i determine if that position in the array has never been assigned. – V_Stack Jul 24 '13 at 08:23
  • @AndreyT Why [`int array[] = {};`](http://codepad.org/Q3RNPv32) is valid code **?** I do not understand it? – Grijesh Chauhan Jul 24 '13 at 08:24
  • @YuvinNg you cannot determine that, unless you keep track of it yourself. – juanchopanza Jul 24 '13 at 08:24
  • @Yuvin Ng: You can't. That is unless you have a "reserved" value that can be used to mark "unused" elements. (For example, if you know tha you will never encounter `INT_MIN` in your application, you can use `INT_MIN` to fill the array initially.) Otherwise, you have to implement it by other means. – AnT stands with Russia Jul 24 '13 at 08:24
  • @YuvinNg, You might just want a `std::map`. – chris Jul 24 '13 at 08:25
  • 1
    @Grijesh Chauhan: `int array[] = {};` is not valid code. `int array[5] = {};` is. When you use `{}` initilizer, the array size has to be specified explicitly. – AnT stands with Russia Jul 24 '13 at 08:25
  • @AndreyT I given a link at code http://codepad.org/Q3RNPv32 surprisingly its working – Grijesh Chauhan Jul 24 '13 at 08:26
  • @GrijeshChauhan, That's a GCC extension. – chris Jul 24 '13 at 08:26
  • @AndreyT all right i tested int arr[5] = {}; and it make those garbage value into 0. that great, i would like to know if its possible to assign other value other than zero? let say -1 to represent it is "empty position".Thanks – V_Stack Jul 24 '13 at 08:27
  • @YuvinNg, `std::fill`. – chris Jul 24 '13 at 08:27
  • Anyway, the most general way for not yet used elements, without using a map or something, would be `boost::optional`, soon to be standard. – chris Jul 24 '13 at 08:29
  • @Antonio: There no documentation for the behavior that is simply undefined. The explanation for the potential reasons for the instability can be found here http://stackoverflow.com/questions/17394907/c-is-an-indeterminate-value-indeterminable – AnT stands with Russia Jul 24 '13 at 08:30
  • 1
    @Grijesh Chauhan: It means that the compiler running under codepad has very loose error checking. It probably interprets it as an array of size zero. Such arrays are explicitly illegal in C and C++, but that compiler apparently accepts them as a non-standard extension. – AnT stands with Russia Jul 24 '13 at 08:36
  • @YuvinNg: "randomly insert postive integer into any position in the array" - a better approach is to fill the array from `[0]` through `[99]` - easier to keep track of which elements you've populated - then use the Standard library to shuffle the array elements into random positions - see http://en.cppreference.com/w/cpp/algorithm/random_shuffle – Tony Delroy Jul 24 '13 at 08:42
  • @TonyD, But you should still initialize every element within that index range, right? I would think it needs the ones it's swapping to be. – chris Jul 24 '13 at 08:44
  • @chris: that's exactly right - you initialise all elements then let the shuffle take care of randomising it, instead of randomly selecting positions as you insert, then wondering which ones you haven't populated yet.... – Tony Delroy Jul 24 '13 at 08:59
  • @TonyD, Agreed, but I still think a `std::map` makes it much easier. Add them where you want when you want and it's easy to iterate over the ones there :) – chris Jul 24 '13 at 09:01
  • @chris: most times people ask for something like this, they want to prepopulate all elements so they can start doing random lookups... if that's not the case, they could populate however many they want, sort them, then as new ones arrive pick a random index up to the new size, swapping the current element value to the end if necessary. Using a map for ordered iteration over randomly positioned elements seems unlikely to be useful, but ultimately it depends what Yuvin Ng wants to do, and whether he has the experience to recognise the best suggestion (which could still be `map`). – Tony Delroy Jul 24 '13 at 09:08
  • @TonyD, True, and there's `std::unordered_map` as well, seeing as how the ordering probably isn't important. – chris Jul 24 '13 at 09:12
  • @chris: oops... I mean "..however many they want, SHUFFLE them, then as new...". Separately, if the intent of a `map` or `unordered_map` is to both serve as a free list (i.e. allow quick identification of an unpopulated element = quick insertion), and find a random populated element, what should the keys and values be? Could you even do these two operations - both in better than O(N) time - with either container alone? – Tony Delroy Jul 24 '13 at 09:33
  • @bkausbk: That will initialize `a[0]` with `-12345678` and the rest with zeros. That is not what the OP meant by initializing with "arbitrary values". – AnT stands with Russia Jul 24 '13 at 15:41
  • @AndreyT Ok problem solved, this also compilers with my `gcc`, but if I use ` -pendatic -error` it gives error that array size `0` or -ve. – Grijesh Chauhan Jul 24 '13 at 16:43
  • @bkausbk: Well, yes, it will "initialize the entire array". As I said above, `a[0]` will be initialized with `-12345678`, while the rest will be initialized with zeros. And no, it will not set all elements to `-12345678`, if that's what you mean. You can "test" it if you want. – AnT stands with Russia Jul 25 '13 at 09:08
1

When I tested , I always got negative value.

The (previously) unused memory space seemed filled with the hex code 0xCC. However, as mentioned above -- several times -- you cannot rely on this.

In one of your comments you clarify your task:

im trying to create an int array let say of the size 100 and randomly insert postive integer into any position in the array. If the array is not full. how could i determine if that position in the array has never been assigned[?]

Fill the array with zeros (manually, or per AndrewT's answer). Since you are inserting positive integers only, all you have to test for is !0.

Jongware
  • 22,200
  • 8
  • 54
  • 100
0

The values contained in an unitialized area of memory can be anything, it is implementation depending. The most efficient implementation is to leave the memory as it was, so you will find in your array whatever was contained before. An important note: it is not something you can use as a random value. Some implementation (I have seen that, especially in the past, when compiling and running in debug mode) might put zeros in your memory, but it is uncommon. You simply should not rely on the content of uninitialized area of memory.

To understand if something has not been touched in your array, you can initialize it to some value like DEADBEEF: http://en.wikipedia.org/wiki/Hexspeak

(Unless you are so unlucky that one of the values you have to insert corresponds exactly to DEADBEEF... :) )

Community
  • 1
  • 1
Antonio
  • 19,451
  • 13
  • 99
  • 197
  • Most "debug" implementations won't default initialize to zero because that *hides* errors. They want to use something that will highlight them, like `0xDEADBEEF` in your example, or `0xCCCCCCCC` in MSVC's runtime library. – Cody Gray - on strike Jul 24 '13 at 08:42
  • @CodyGray I am referring to some behaviour I experienced in the past, and I do agree that it was misleading. – Antonio Jul 24 '13 at 08:52
  • @CodyGray: -858993460 should be 0xCCCCCCCC in his example not 0xDEADBEEF. – bkausbk Jul 24 '13 at 09:41
  • 1
    @bkausbk What? I don't understand what you're saying. Whose example? Antonio is just giving random examples of magic numbers. – Cody Gray - on strike Jul 24 '13 at 09:42
  • @CodyGray: I was talking about the original authors question where uninitialized values contains -858993460 which is 0xCCCCCCCC. – bkausbk Jul 24 '13 at 09:49
0

You can't know what this will produce, since it takes as value the bits that are in memory in that moment. So you can get ANY value, not only negative values.

Hoijof
  • 1,343
  • 15
  • 27
0

These are garbage values, you cannot expect to work with these variables properly and they will not predict what it may result into. Whenever a variable gets allocated some portion of memory gets allocated for that variable and those portion may be used previously for some other unknown calculation which you cannot know, so you have to intialize those variables with some values to avoid usage of garbage values.

Saby
  • 718
  • 9
  • 29
0

You are not assigning any value at these locations. So it will return garbage values from memory. You must put some values at these locations. Unimplemented locations will returned in some unexpected/unpredictable values.