Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Microsoft C Compiler: Inline variable declaration?

I'm writing C in Visual Studio 2010. The compiler doesn't seem to want to let me use inline variable declarations. The following code produces an error:

unsigned int fibonacci_iterative(unsigned int n) {
 if (n == 0) {
  return 0;
 }
 if (n == 1) {
  return 1;
 }

 unsigned int prev_prev = 0; // error
 unsigned int prev = 1; // error
 unsigned int next = 0; // error
 for (int term_number = 0; term_number < n; term_number++) {
  unsigned int temp = prev_prev + prev;
  prev = next;
  prev_prev = prev;
  next = temp;
 }
 
 return next;
}

Error:

error C2143: syntax error : missing ';' before 'type'

error C2143: syntax error : missing ';' before 'type'

error C2143: syntax error : missing ';' before 'type'

Why is this happening? Is there a setting to make the compiler not so strict?

like image 227
Nick Heiner Avatar asked Jan 31 '10 02:01

Nick Heiner


People also ask

What is inline variable declaration?

The new inline variable declaration syntax allows you to declare the variable directly in a code block (allowing also multiple symbols as usual): procedure Test; begin var I: Integer; I := 22; ShowMessage (I. ToString); end; procedure Test2; begin var I, K: Integer; I := 22; K := I + 10; ShowMessage (K.

Can you write C in Visual Studio?

The Microsoft C/C++ for Visual Studio Code extension supports IntelliSense, debugging, code formatting, auto-completion. Visual Studio for Mac doesn't support Microsoft C++, but does support . NET languages and cross-platform development.

How do you declare in CPP?

A C++ program might contain more than one compilation unit. To declare an entity that's defined in a separate compilation unit, use the extern keyword. The information in the declaration is sufficient for the compiler.

What is declaration in C?

A "declaration" establishes an association between a particular variable, function, or type and its attributes. Overview of Declarations gives the ANSI syntax for the declaration nonterminal. A declaration also specifies where and when an identifier can be accessed (the "linkage" of an identifier).


1 Answers

Putting declarations after non-declarations isn't allowed in C89, although it is allowed in C++ and in C99 (MSVC still doesn't support C99, though).

In C89, you can achieve a similar effect by using a nested block:

unsigned int fibonacci_iterative(unsigned int n) {
    if (...) {
    }

    {
       unsigned int prev_prev = 0;
       unsigned int prev = 1;
       unsigned int next = 0;
       ...
    }
 }
like image 97
jamesdlin Avatar answered Sep 23 '22 07:09

jamesdlin