Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Y does not name a type" error in C++

I don't know what to search to find an explanation for this, so I am asking.
I have this code which reports error:

struct Settings{
    int width;
    int height;
} settings;

settings.width = 800; // 'settings' does not name a type error
settings.height = 600; // 'settings' does not name a type error

int main(){
    cout << settings.width << " " << settings.height << endl;

but if I put the value assignment in main, it works:

struct Settings{
    int width;
    int height;
} settings;

main () {
    settings.width = 800; // no error
    settings.height = 600; // no error

Can you explain me why?

EDIT:
Regarding to Ralph Tandetzky's answer, here is my full struct code. Could you show me how to assign the values as you did with my snippet struct?

struct Settings{
    struct Dimensions{
        int width;
        int height;
    } screen;

    struct Build_menu:Dimensions{
        int border_width;
    } build_menu;
} settings;
like image 367
Qwerty Avatar asked Jun 05 '13 11:06

Qwerty


People also ask

What does the error does not name a type mean?

The "error does not name a type" in C/C++ is defined as the when user declares outside of the function or does not include it properly in the main file this error will through.

How do you name a type in C++?

C++ code. Use CamelCase for all names. Start types (such as classes, structs, and typedefs) with a capital letter, other names (functions, variables) with a lowercase letter.

How do you fix a undefined reference in C++?

When we compile these files separately, the first file gives “undefined reference” for the print function, while the second file gives “undefined reference” for the main function. The way to resolve this error is to compile both the files simultaneously (For example, by using g++).


1 Answers

You cannot put assignments outside the context of a function in C++. If you're puzzled by the fact that you sometimes saw the = symbol being used outside the context of a function, such as:

int x = 42; // <== THIS IS NOT AN ASSIGNMENT!

int main()
{
    // ...
}

That's because the = symbol can be used for initialization as well. In your example, you are not initializing the data members width and height, you are assigning a value to them.

like image 183
Andy Prowl Avatar answered Oct 21 '22 10:10

Andy Prowl