Search notes:

C: if statement

Variable declaration in an if statement

A variable cannot be declared within an if statement. The following simple program, which tries to do that, when compiled with gcc, reports the error expected expression before 'int'.
#include <stdio.h>

int foo() {
  return 42;
}

int main() {

   if (int i = foo()) {  // error: expected expression before ‘int’

      printf("i = %d\n", 42);

   }
   else {

      printf("foo returned 0\n");

   }
}
Github repository about-c, path: /language/statements/compound/if/variable-declaration.c
See also the Stack Overflow question Declare variable in if statement (ANSI C)

Index