0

When I make my own struct, say:

struct myStruct{
    int data1;
    int data2;
    string data3;
}

I can initialize an instance of type myStruct like this:

myStruct instance1;

So my question is, why am I often seeing "struct" written during the initialization of a struct? Maybe that's an inaccurate statement so here is an example of what I mean:

/*This is a tiny program that checks
  to see if a file exists in
  the current working directory. */

#include <sys/stat.h>
#include <iostream>
using namespace std;

const string FILENAME = data.txt;

int main(){

    struct stat fileStatus; //<-- HERE HERE HERE!
    if (FileExists(FILENAME, fileStatus)){
        cout << "File Does Exist" << endl;
    }else{
        cout << "File Does NOT Exist" << endl;
    }

    return 0;
}

bool FileExists(const string & fileName,struct stat & fileStatus){

    bool fileDoesNotExist = stat (fileName.c_str(), &fileStatus);
    return !fileDoesNotExist;
}

> LINE 13: struct stat fileStatus;

Is this something that was done in C for some reason?
Something with a macro or a typedef?

I just don't understand why this is the way it is.

0

2 Answers 2

6

This is a C thing; there's no good reason to continue to do it in C++.1

In C, struct is part of the typename, e.g.:

struct foo { int x; };

defines a type called struct foo. In C++, it defines a type called foo. In C, you can usually hide this irritation behind a typedef:

typedef struct foo { int x; } foo;


1 At least, not in code that couldn't possibly also be compiled as C (such as the example in your question).

Sign up to request clarification or add additional context in comments.

2 Comments

This is one part of C and C++ that are fundamentally incompatible. If you were to have struct A { int x; }; typedef struct A B; struct B { int x; }; it is legal C but not legal C++.
struct foo and foo are two different things in C++, too. See the classic example of struct stat and function stat.
-2

You can do what you want by instead calling it like this:

typedef struct mystruct
{
    int itema;
    int itemb;
Etc...
}* mystruct;

So that's whenever you make a mystruct item it creates a pointer to your struct, else you have to call your struct by

struct mystruct *object;

2 Comments

Typedefing struct mystruct * to mystruct sounds like a very bad idea.
@OliCharlesworth: So bad, in fact, that I'm sure a Java programmer thought of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.