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)

  • 2
    In such questions, you should indicate which error message you see (its text), as well as which compiler you use (for example, gcc version xxx) and with which keys you call it. And in your case, let's say gcc with the -std=gnu99 compile 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

2 answers 2

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]; } 
  • Not. In the 1st case - IntelliSense: id "j" is not defined - Olfy
  • Oops. In fact, a semicolon. It works without it. Thank. - Olfy
  • @Olfy: Please! - VladD pm

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]; } 
  • one
    Perhaps) But it still means that in C it is affected by the standard and there may be a situation when you do not declare, unlike C ++. - Andrei Kurulyov