Consider the following program:
Many people when they want to use a struct, they create a new variable as:
struct structureName variableName
While it works when you just define it as:
structureName variableName
My teacher always uses the first method. My question is how do they differ? Do I ever need to specify struct before defining my variableName. Here is an example to explain my question:
struct example {
int n;
char c;
};
int main() {
example o;
o.c = 'c';
o.n = 5;
printf("%c", o.c);
printf("%dn", o.n); //this works
struct example ex; // this versus "example o" without using struct keyword
ex.c = 'e';
ex.n = 7;
printf("%c", ex.c);
printf("%d", ex.n); //this works
return 0;
}
3
This is one of the differences between C and C++.
In C, structure names are completely separate from other names and you must use the struct
keyword to tell the compiler to look for the name of a structure.
Another way to put it is that the struct
keyword is actually part of the name of the structure.
When designing C++, this was changed and the use of the struct
(or class
) keyword was made optional when referring to a structure or class.
1