Thread: Basic Typedef question

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    51

    Basic Typedef question

    Whats the difference between doing:

    Code:
    typedef struct myStruct {
    
          int a;
          int b;
    };
    and

    Code:
    typedef struct {
          int a;
          int b;
    } myStruct;
    They both seem to do the same thing and produce the same results:

    Code:
    myStruct ms;
    ms.a = 3;
    ms.b = 4;

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    You don't need the typedef in the first case there.
    Yes they are the same but the first one without the typedef is the preferred way in C++.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    You should be getting a warning for the first version. It doesn't actually typedef anything. If you replace the struct {} part with a simpler type, say "int," it would look like:

    Code:
    typedef int;
    Which is meaningless, and I'm surprised it does compile at all (it does compile though, at least with VC9)
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. question about typedef
    By rob90 in forum C Programming
    Replies: 3
    Last Post: 12-14-2009, 06:01 AM
  2. Very basic C question
    By cnewbie1 in forum C Programming
    Replies: 8
    Last Post: 11-30-2009, 08:53 AM
  3. basic question about global variables
    By radeberger in forum C++ Programming
    Replies: 0
    Last Post: 04-06-2009, 12:54 AM
  4. Help if basic question
    By Sshakey6791 in forum C++ Programming
    Replies: 9
    Last Post: 02-28-2009, 04:00 PM
  5. typedef struct question
    By flevine100 in forum C Programming
    Replies: 1
    Last Post: 09-03-2002, 09:34 PM