In your code you have defined multiple instances of both i
and j
(each instance occupying its own memory space). At the very least this results in difficult to understand and unmaintainable code:
int i = 0, int j = 0; //i & j defined here
for(int i = 0; i < 10; i++){//and new i here
static int j = 0;//new j defined here with new block scope.
About scope: This code snippet is meaningless except to illustrate that each occurrence of i
is a separate variable because of block scope, each having its own memory location: (where block scope is created using brackets {...}
)
int main(void) {
int i = 2; //will remain == to 2
if(1)
{//new scope, variables created here with same name are different
int i = 5;//will remain == 5
for(int i = 8;;)
{//new scope again, variable with same name is not the same
int i = 0;
}
i = 20;// which i is it that we just changed here?
}
i = 30;// or here?
return 0;
}
The take away is not to do it. Use unique and descriptive names with proper scope to avoid this ambiguity.
...how to access the variables i and j defined outside the for-loop in
the main file...
Example 1: If variables are declared with global scope (eg. outside of a function in a .c file) then they are accessible everywhere in the file:
File.c
...
int gI=0, gJ=0; //defined with file global scope outside of a function
void another_func(void);
...
int main(){
for(gI = 0; gI < 10; gI++){
gJ++;
printf("gJ: %d, gI: %d \n", gJ,gI);
}
printf("gJ: %d, gI: %d \n", gJ,gI);//values printed here...
another_func();
return 0;
}
void another_func(void)
{
printf( "gI = %d\ngJ = %d\n", gI, gJ);//...are the same here
}
Example 2: Alternately, you can declare variables with extern scope in a header file, where they can be accessible in any file that includes that header file:
file.h
...
extern int gI; //declared here, with extern scope (can see and use in another file)
extern int gJ; //ditto
void another_func(void);//prototype callable from multiple .c files
...
File.c
#include "file.h"
...
int gI=0; // initialize extern (only one time) before using anywhere.
int gJ=0; // The values of these variables are visible in any .c file
// that #includes the header that they were created in.
...
int main(){
for(gI = 0; gI < 10; gI++){
gJ++;
printf("gJ: %d, gI: %d \n", gJ,gI);
}
printf("gJ: %d, gI: %d \n", gJ,gI);//values printed here...
another_func();//...are the same here
return 0;
}
File2.c
#include "file.h"
...
void another_func(void)
{
printf( "gI = %d\ngJ = %d\n", gI, gJ);//extern scope variables accessible here
}