Thread: Difference between defining and declaring a variable?

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    11

    Difference between defining and declaring a variable?

    What is the difference between defining and declaring a variable?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by ak22
    What is the difference between defining and declaring a variable?
    Well...
    Quote Originally Posted by C99 Clause 6.7 Paragraph 5
    A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:
    • for an object, causes storage to be reserved for that object;
    • for a function, includes the function body;
    • for an enumeration constant or typedef name, is the (only) declaration of the identifier.
    In practice, this means that most of the variable declarations that you will encounter are definitions, except for those declared extern.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Defining a variable allocates memory for it, and if written such, initializes it.

    Declaring a variable merely makes an identifier for something of some type but no memory is set aside.

    The difference doesn't come up often in code, because declarations are usually definitions at the same time, but one example goes like this:
    Code:
    extern type foo;
    
    type foo;
    While type foo; can only appear in one source file, the extern line is probably in many files, including the one that defines foo. The extern line is a declaration, but not a definition.

    edit - beaten to it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. defining & declaring
    By joybanerjee39 in forum C Programming
    Replies: 2
    Last Post: 11-24-2011, 04:15 AM
  2. Declaring classes and defining later?
    By jw232 in forum C++ Programming
    Replies: 4
    Last Post: 04-24-2008, 04:13 PM
  3. Declaring a struct before defining it
    By hardi in forum C Programming
    Replies: 4
    Last Post: 12-07-2006, 01:51 PM
  4. Difference between typdefing and declaring structs
    By Ganoosh in forum C++ Programming
    Replies: 5
    Last Post: 07-21-2005, 12:11 AM
  5. Replies: 5
    Last Post: 06-01-2002, 11:24 PM