for statement-repeated syntax

You can write iteratively using the for statement.

for (Initialization of loop variable; Iteration condition; Update of loop variable) {
  
}

This is a sample to calculate the total with the for statement.

#include <stdint.h>
#include <stdio.h>

int main (void) {
  
  // Find the total with a for statement
  int32_t total = 0;
  int32_t i;
  for (i = 0; i <10; i ++) {
    total + = i;
  }
  
  printf("%d\n", total);
}

The total from 0 to 9 is output.

45 45

The for statement is syntactic sugar for while statement. The following while statement and for statement are equivalent.

#include <stdint.h>
#include <stdio.h>

int main (void) {
  
  // Find the total with a for statement
  int32_t total = 0;
  int32_t i = 0;
  while (i <10) {
    total + = i;
    i ++;
  }
  
  printf("%d\n", total);
}

Variable declaration in the loop variable initialization part of for added in C99

Variable declaration in the loop variable initialization part of for added in C99 The function is convenient.

for (declaration and initialization of loop variables; repeat condition; update of loop variables) {
  
}

This is a sample to calculate the total with the for statement. Initialization is performed at the same time as variable declaration using the function of C99.

#include <stdint.h>
#include <stdio.h>

int main (void) {
  
  // Find the total with a for statement
  int32_t total = 0;
  for (int32_t i = 0; i <10; i ++) {
    total + = i;
  }
  
  printf("%d\n", total);
}

It is semantically syntactic sugar with the following code.

#include <stdint.h>
#include <stdio.h>

int main (void) {
  
  // Find the total with a for statement
  int32_t total = 0;
  {
    int32_t i;
    for (i = 0; i <10; i ++) {
      total + = i;
    }
  }
  
  printf("%d\n", total);
}

If it's a new gcc, I think it works without options. For older gcc, add the following options.

gcc -std = c99 -o a a.c && ./a

gcc -std = gnu99 -o a a.c && ./a

Associated Information