Hack Forums
[C] EXTREMELY simple question (about C, not C++). - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C] EXTREMELY simple question (about C, not C++). (/showthread.php?tid=3182609)



EXTREMELY simple question (about C, not C++). - antigrav - Jan 16, 2013

EDIT: I'm a huge fucking dumbass. For those who might one day find this thread by search, let this serve as a lesson: apparently, you need to declare variables in the beginning of a code block. Example below.
Code
#include <stdio.h>
int main()
{
    int x = 0;  //all I did was switch the first two lines
    printf("I hate Hello World. So boring... \n");  //all you need to do is make sure variables are declared at the top
    if(x==0){
        printf("wat?");
    }
    getchar();
    return 0;
}

Decided to get into a little C, being a native Python user. I literally just learned syntax today. Anyways, after typing some very basic code that SHOULD compile:

Code
#include <stdio.h>
int main()
{
    printf("I hate Hello World. So boring... \n");
    int x = 0;
    if(x==0){
        printf(".-.");
    }
    getchar();
    return 0;
}

I'm getting errors. For some background, I'm using MSVC++2010 Express, and I've named the file main.c rather than main.cpp...

Here are the errors:
Code
1>c:\users\arnav\documents\visual studio 2010\projects\omfg\omfg\main.c(5): error C2143: syntax error : missing ';' before 'type'
1>c:\users\arnav\documents\visual studio 2010\projects\omfg\omfg\main.c(6): error C2065: 'x' : undeclared identifier

I've been Googling the errors, but they are usually not found in simple programs such as this, and honestly, after Googling, I still have NO idea why it isn't compiling.

Thoughts?


* - ( ͡° ͜ʖ ͡°) - Jan 16, 2013

So the first code is compiling, and the second one isn't?


* - antigrav - Jan 16, 2013

(Jan 16, 2013 06:32 PM)Subotai Wrote:  So the first code is compiling, and the second one isn't?

Indeed. I think I've figured it out though, you need to declare variables at the beginning of code.


* - Super Effective - Jan 16, 2013

Both of those should compile successfully, I don't know why you're having trouble. I know some compilers force you to declare variables at the top, but I wasn't aware MSVC was one of them.

Also, changing the extension to .cpp instead of .c might fix that problem. You can still use C headers and use C functions in a .cpp file. You can also look into getting MinGW and using gcc under Windows.


* - notsteve - Jan 16, 2013

c89 (what gcc considers ANSI) only allows variables declared at the beginning of functions. c99 (actual ANSI) doesn't have this requirement.