Trevor Hickey
Trevor Hickey

Reputation: 37806

(C/C++) struct initalization syntax

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.

Upvotes: 1

Views: 6057

Answers (2)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

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).

Upvotes: 6

Aaron K
Aaron K

Reputation: 437

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;

Upvotes: -3

Related Questions