typedef struct error{int warning, error, exception;}error;
main()
{
error g1;
g1.error =1;
printf("%d",g1.error);
}
Here is code sample of whose output is 1.
But I need a explanation of how this code is working ?
typedef struct error{int warning, error, exception;}error;
main()
{
error g1;
g1.error =1;
printf("%d",g1.error);
}
Here is code sample 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.
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.