raitisd
raitisd

Reputation: 4435

While following a tutorial I'm getting an error: C++ requires a type specifier for all declarations

I have some experience with python and php but now decided to learn a bit of C++. I'm following a tutorial on http://www.tutorialspoint.com/cplusplus/cpp_data_types.htm. But I am getting an "error: C++ requires a type specifier for all declarations".

Here is what the tutorial says:

For example, the following code defines an enumeration of colors called colors and the variable c of type color. Finally, c is assigned the value "blue".

enum color { red, green, blue } c;
c = blue;

Here is my code:

#include <iostream>
using namespace std;

enum color {red, blue, green} c;

c = green;

int main()
{
        cout << c << endl;
        return 0;
}

When I'm trying to compile I get this error:

someuser@somemac:~/cpp/cpptut$ g++ enum.cpp
enum.cpp:6:1: error: C++ requires a type specifier for all declarations
c = green;
^
1 error generated.

It seems to me that I do everything exactly as its said in the tutorial. Is there a mistake in the tutorial?

Upvotes: 2

Views: 1395

Answers (2)

kebs
kebs

Reputation: 6707

You are declaring a global variable, you need to declare the type, then instantiate the variable:

enum color {red, blue, green};

color c = green;

int main()
{
   ...
}

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409176

You can't have loose statements in the global scope, you need to put it inside a function, or initialize the variable at time of definition.

So either

enum color {red, blue, green} c = green;

or

enum color {red, blue, green} c;

int main()
{
    c = green;
    ...
}

Upvotes: 3

Related Questions