declaration or definition

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pgupta0609
    New Member
    • Mar 2010
    • 4

    declaration or definition

    if i write a statement in C/C++..........

    main()
    {
    int x;
    }

    is this a declaration or definition?

    if this is a declaration then why it display garbage value for x?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    That doesn't display any value for x there is no output statement.

    It is a definition because it actually causes the compiler to allocate memory space to use for the variable x, however using an automatic scope variabole without initialising it is undefined behaviour.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      A declaration says that somewhere there is a variable or function named foo.

      A definition says here is a variable or function named foo.

      Comment

      • Dheeraj Joshi
        Recognized Expert Top Contributor
        • Jul 2009
        • 1129

        #4
        Code:
        int x;
        is a declaration.

        Regards
        Dheeraj Joshi

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          Originally posted by dheerajjoshim
          Code:
          int x;
          is a declaration.
          No its a definition, it actually defines the variable, causes the compiler to allocate memory for it.

          Comment

          • donbock
            Recognized Expert Top Contributor
            • Mar 2008
            • 2427

            #6
            If the following statement appears in multiple files, then it is a definition in one of them and a declaration in all the others. It can be difficult to predict which instance turns out to be the definition.
            Code:
            extern int x;
            I can't think of a way other than extern to create a variable declaration.

            I think the confusion comes because many people casually refer to variable declarations. Pedants (I'm not naming any names, but I'm one of them) point out that the C Standard has precise definitions for the terms definition and declaration that differ from casual usage.

            It is entirely possible that these precise definitions differ from Standard usage in other languages. That's another source of confusion -- words can change their meaning depending on the context in which they are used.

            Comment

            Working...