Why is this option not allowed?
int sum=0; for(int j=0; j<n; j++); { sum+=mas[0][j]; sum+=mas[n-1][j]; } And this one compiles:
int sum=0; int j=0; for( ; j<n; j++); { sum+=mas[0][j]; sum+=mas[n-1][j]; } (mas is already initialized)
I think both variants are compiled, only the first one gives a warning because this code contains undefined behavior.
The variable sum will not be initialized for you by the compiler. And the use of an uninitialized variable is not even unspecified, but undefined behavior. This means that not only “the initial value of a variable can be anything,” but “when executing a program, anything can happen, including formatting a hard disk.”
Ok, the question has been edited, now both variables are initialized, we are looking further.
But I did not notice another mistake. You have written for(int j=0; j<n; j++); , a semicolon at the end is superfluous.
As a result, in the first case, the variable j local in the block and is not visible beyond its limits: this code can be equivalently written like this:
for(int j=0; j<n; j++) ; { sum+=mas[0][j]; sum+=mas[n-1][j]; } As far as I know, in C, in principle, you cannot declare variables inside for . (inside round brackets).
As I corrected in the comments, this is up to standard C99. Standards C99 and above behave in this case, as in C ++
int sum; int j; for(j=0; j<n; j++){ sum+=mas[0][j]; sum+=mas[n-1][j]; } In C ++, such a construction is admissible, but these variables are visible only inside this cycle. In the author’s example, the loop block ends with a semicolon, which is why in the next block the compiler does not know anything about j .
//Скомпилируется int sum; for(int j=0; j<n; j++){ sum+=mas[0][j]; sum+=mas[n-1][j]; } //Не скомпилируется int sum; for(int j=0; j<n; j++); //Область видимости j ограничена этой строкой { sum+=mas[0][j]; sum+=mas[n-1][j]; } Source: https://ru.stackoverflow.com/questions/484887/
All Articles
gccwith the-std=gnu99compile both options (of course, if it’s superfluous;remove), and only the second one without it. Compiler keys can be viewed in man gcc - avp