The use of error by struct keyword
typedef struct error{int warning, error, exception;}error;
main()
{
error g1;
g1.error =1;
printf("%d",g1.error);
}
Here is code sampl开发者_开发知识库e of whose output is 1.
But I need a explanation of how this code is working ?
Let's start with the inside of the onion:
struct error
{
int warning, error, exception;
};
That defines a struct called error
with 3 elements: warning
, error
, and exception
.
To use it, you could have replaced the error g1;
line in your main
function with struct error g1;
. Then you wrap that struct definition in a typedef, which essentially tells the compiler that there's a type error
that's equivalent to struct error
. The names are all in independent spaces: types, a struct, and elements in that struct. So they don't clash. That said, it's a bit cleaner to write
typedef struct
{
int warning, error, exception;
} error;
since it doesn't give the struct 2 names. The first version I gave is also valid; some people prefer to be explicit about their usage of structs.
What is it that you don't understand in this code? error
is not a reserved word in C, so you are free to use it as a (variable/struct) name.
You defined a struct
containing 3 int
fields, instantiated it as a local variable g1
, assigned 1 to one of its fields, then printed that field on the standard output. If you have any more specific questions, please clarify.
You defined a struct error
that has an int
member named error
. You defined a typedef (in other words, an alias) for struct error
, named error
. You then created an instance of struct error
, named g1
, using the typedef name. Then, you assigned the value 1
to the error
member of the error
instance g1
. Finally, you printed the value of g1.error
.
Struct names and typedef names occupy separate namespaces — they can be the same. In C, you must put the keyword struct
before structs' names:
struct S{ /*...*/ };
struct S instance1;
But not before typedef names:
struct S{ /*...*/ };
typedef struct S S;
S instance2;
You can also typedef unions and enums. You can combine a struct definition with a typedef definition:
typedef struct S { /* ... */ } S;
And you can omit the struct name:
typedef struct { /* ... */ } S;
In this case, the struct type can only be referred to via the typedef.
This is a pretty basic use of a typedef struct in c. I'd recommend you visit the wikipedia page on structs for a general overview, but in short:
The first line creates a new structure type struct error
which contains 3 integers: warning
, error
, and exception
. The typedef acts as an alias renaming the struct error
to just error
so you can refer to items of this type by just the short name.
The code inside main then creates a new error
on the stack, sets its error
property to 1, and then prints it out.
精彩评论