-2
// A simple program that computes the square root of a number
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, char *argv[])
{
  if (argc < 2)
  {
    fprintf(stdout,"Usage: %s number\n",argv[0]);
    return 1;
  }

  double inputValue = atof(argv[1]);
  double outputValue = sqrt(inputValue);
  fprintf(stdout,"The square root of %g is %g\n",
          inputValue, outputValue);
  return 0;
}

I received the following errors

Error 1 error C2143: syntax error : missing ';' before 'type'
Error 2 error C2143: syntax error : missing ';' before 'type' Error 3 error C2065: 'inputValue' : undeclared identifier
Error 4 error C2065: 'outputValue' : undeclared identifier

Adam Lee
  • 24,710
  • 51
  • 156
  • 236
  • 2
    Compiles for me. Me thinks that code is not a 1:1 translation. – Ed S. Jun 18 '12 at 22:50
  • 2
    BTW, if `inputValue` is `0` after the call to `atof`, did the user enter `0` or something invalid? (HINT: you can't know) – Ed S. Jun 18 '12 at 22:52
  • Visual C++ automatically selects C or C++ depending on the extension (.c or .cpp). If it's compiling it as C, then here's one of many duplicates that will answer your question: http://stackoverflow.com/questions/8496853/why-does-this-code-not-compile – Mysticial Jun 18 '12 at 22:54
  • @Mysticial Sounds spot on to me – Captain Obvlious Jun 18 '12 at 23:01

1 Answers1

4

If you name the file .cpp, it should compile and run fine.

If you name the file .c, however, it will fail.

The reason is that you need to declare all variables at the top of a C function; you cannot declare them at point of use.

paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • Yes, but the reason behind that is that VS only implements C89. In C99 you can declare variables wherever you like in a function. Damn you MS for not showing love to us C fanatics... – Ed S. Jun 18 '12 at 22:55
  • I've lost track of what version of VS purports to support which version of C ;) But clearly, MSVS2010 doesn't fully support C99 ;) – paulsm4 Jun 18 '12 at 22:57
  • It's a conspiracy, period. MS probably wants C to die as much as Linux. – Mysticial Jun 18 '12 at 22:58
  • @EdS: Herb Sutter also publicly stated that they will never will support newer versions on [his blog](http://herbsutter.com/2012/05/03/reader-qa-what-about-vc-and-c99/). – Jesse Good Jun 18 '12 at 22:58
  • @JesseGood: Yep, I saw that. VS is C89 and will be forever unless MS changes its mind. – Ed S. Jun 18 '12 at 23:06
  • [MSVS2010 should support C95](http://msdn.microsoft.com/en-us/library/sk54f3f5.aspx) I'm not sure it's *complete* support, and you need to do some "extra stuff": http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvc/thread/d0c999ec-d2f9-4e61-8b53-0b3d6535f18f/ – paulsm4 Jun 18 '12 at 23:12