-1

I was looking at piece of code here that I was gonna use:

#include <sys/stat.h>

struct stat sb;

if (stat(pathname, &sb) == 0 && S_ISDIR(sb.st_mode))
{
    ...it is a directory...
}

I suppose that if I'm going to use it, I should probably understand what it does. My question is about the line

struct stat sb;

What does that mean? I've known struct in the sense of declaring it like

struct node { int val; node * next; }

and so I'm confused about why there are 2 tokens after the struct declaration.

Community
  • 1
  • 1
Steve Jobs
  • 181
  • 5
  • 2
    It creates an instance of `struct stat`. – R Sahu Feb 23 '15 at 15:49
  • @RSahu Why not just `stat sb` then? Why the `struct`? – Steve Jobs Feb 23 '15 at 15:51
  • Although in this case, everything should work the same for C and C++, you should really decide which one of the two tags you want to keep! – Marcus Müller Feb 23 '15 at 15:51
  • 4
    When programming in `C`, you'll have to use `struct stat sb;`.You can use `stat sb;` only if a `typedef` has been created using `typedef struct stat stat;` – R Sahu Feb 23 '15 at 15:52
  • possible duplicate of [Is \`struct\` keyword needed in declaring a variable of structure?](http://stackoverflow.com/questions/11364653/is-struct-keyword-needed-in-declaring-a-variable-of-structure) – Joel Feb 23 '15 at 16:05

2 Answers2

2

In C, a struct is not automatically a typename, so you have to refer to struct name with struct foo. Similarly, you need to use enum bar or union baz. People often use typedef to avoid typing struct when declaring instances.

In C++, that keyword is optional because structures, enumerations and unions (plus classes) are types, but you can still write class std::string s = "abc";. Concerning stat, there is both a structure and a function with that name and in order disambiguate between the two, you need to write struct stat when referring to the structure.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
0

this

struct node { int val; node * next; }

is what you could call the definition of the type "struct stat" this

struct stat sb;

just create a struct of that type (which has already been defined somewhere else) for example in stat.h ;-)

Guiroux
  • 531
  • 4
  • 11
  • 1
    "creates a struct" is not close enough. It's a variable initialization of `struct stat` type. – zoska Feb 23 '15 at 16:42