Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio "illegal use of this type as an expression"

I've just started using Visual Studio (I got VS 2012 from dreamspark, and it hasn't been long since I've started using Windows again) and I'm having some trouble.

I have a single file named "main.c" under my Source Files folder that looks like this:

#include <stdio.h>

typedef struct S_s S;
struct S_s {
    void* x;
};

int main(int argc, char** argv)
{
    int N;
    scanf("%d", &N);

    S* s;
    printf("%p", s);

    return 0;
}

And when I try to build it gives me the following error messages:

Error   3   error C2065: 's' : undeclared identifier    c:\users\math4tots\documents\visual studio 2012\projects\algorithms\lecture1\main.c 13  1   Lecture1
Error   4   error C2065: 's' : undeclared identifier    c:\users\math4tots\documents\visual studio 2012\projects\algorithms\lecture1\main.c 14  1   Lecture1
Error   2   error C2275: 'S' : illegal use of this type as an expression    c:\users\math4tots\documents\visual studio 2012\projects\algorithms\lecture1\main.c 13  1   Lecture1

The funny thing is that it builds just fine if I comment out the scanf line.

I did create an "Empty project" under the "Visual C++" options so I wasn't sure if VS compiled it as a C or C++ program. However, I was under the impression that my code was C/C++ agnostic enough that it should compile in either C or C++.

What can I do to get this to build while still maintaining the semantics of the program?

like image 565
math4tots Avatar asked Aug 28 '12 18:08

math4tots


2 Answers

The code is legal C++ and legal C99, but not legal C89. Variable declarations in C89 must come at the beginning of a block, so having S* s; after scanf("%d", &N); is not OK in C89.

like image 187
Johan Råde Avatar answered Sep 23 '22 13:09

Johan Råde


Haven't tried it, but old C rules (prior to C99) only allowed declaration of auto variables at the beginning of a block. So under those rules, the intervening scanf makes the declaration S* s illegal. Commenting out the scanf "fixes" the problem. This has always been legal in C++.

like image 44
Pete Becker Avatar answered Sep 23 '22 13:09

Pete Becker