How is this code working?

Question:Given the list of numbers, you are to sort them in non decreasing order.

When the array c[] is not assigned any value after i>=t in the for loop, how's the code gonna compile successfully?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <cstdio>
using namespace std;
main()
{
    int t;
    scanf("%d",&t);
    int *a = new int[t+1];
    int *b = new int[t+1];

    for(int i=0;i<t;i++)
        scanf("%d",&a[i]);

    int c[1000001];
    for(int i=0;i<t;i++) //What about c[t], c[t+1], ...??? 
        c[i]=0;

    for(int i=0;i<t;i++)
        c[a[i]]=c[a[i]]+1;

    for(int i=1;i<=1000001;i++)
        c[i]=c[i]+c[i-1];

    for(int i=t;i>=0;i--)
    {
        b[c[a[i]]]=a[i];
        c[a[i]]=c[a[i]]-1;
    }

    for(int i=1;i<=t;i++)
        printf("%d\n",b[i]);

    return 0;
} 
Last edited on
An uninitialized variable holds garbage, so trying to use it may be considered a logic error.
Compilers may issue a warning when they detect that and you can translate such warnings to compile errors. However it is not a requirement, and the detection may fail.

gcc fails in this, clang reports it correctly
1
2
3
int foo;
for(int K=0; K<foo; ++K) //here
   foo += K; //and here 


both fail in
1
2
3
int foo[2];
for(int K=0; K<42; ++K)
	foo[0] += foo[1];



By the way, you've got another error. In the loop of line 20 you are trying to access `c' out of bounds
(valid index are from 0 to 1000000)
Ya..What you said in the last is also right!
But codechef's accepting the code for the problem:
http://www.codechef.com/problems/TSORT

So how does it(a compiler which doesn't detect the error) interpret an uninitialized variable?
For example in the case 1 you were telling about, how does clang interprets the value of foo?

Ps: Thanks for replying! (:
Topic archived. No new replies allowed.