Arrays are strange

Consider the two following C++ programs

  • Program A:
1
2
3
4
5
6
7
8
9
#define L 1000

int main() {
    int array[L][L];
    for (int i=1; i < L; i++)
        for (int j=1; j < L; j++)
            array[i][j] = i*j;
    return 0;
}

  • Program B:
1
2
3
4
5
6
7
8
9
#define L 1000

int main() {
    int array[L][L];
    for (int j=1; j < L; j++)
        for (int i=1; i < L; i++)
            array[i][j] = i*j;
    return 0;
}

Usually, one would expect them to run typically in the same time. Do they?

Program B is slightly faster Program A is slightly faster Both programs run in the same time

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Hasmik Garyaka
Sep 12, 2017

Compiler will increment pointer in A case to access linearly stored data. In case b it can't do it. It depends on compiler optimization.

Yep.

How can the compiler so optimize such that in Case B, it works faster? By allocating the data in a different way?

Agnishom Chattopadhyay - 3 years, 9 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...