swapping variables is messing things up..

what the heck is going on with this program? the result I get is 1606422622, but why????

#include <iostream>
using namespace std;


int main(){
int j;
int i = j;

for (j=0; j<1; j++) {
cout << i;
}

return 0;
}
Actually, it's indifinite. You never initialize a value for j, causing it to go haywire.
When posting code, please add code tags. Highlight the code and press the <> button on the right of the edit window. Here is your code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;


int main(){
int j;
int i = j;

for (j=0; j<1; j++) {
    cout << i;
}

return 0;
} 

At line 6 j is uninitialized so it contains whatever random bits happen to be at the location assigned to it. Line 7 assigns i to the uninitialized value of j. Line 10 prints it. If you assign something to j at line 6 then it will print that value.
arent I initializing it in the for statement?
You assign a value to j in the for loop. However, the assignment of j to i occurs before j is assigned or initialized to any value.
Try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
// using namespace std;

int main() {

    int i ;

    for( int j=0; j<1;  ++j /*j++*/ ) {

        i = j ; // assign to i *after* giving a well-defined value to j
        std::cout << i << ' ' ;
    }

    // return 0;
}
Topic archived. No new replies allowed.