0
#include <stdio.h>

int main()
{
   int a;       
   printf("%d\n",a);
}

The statement in the above example: int a; — is it a declaration or definition? If it is a declaration, the printf() statement should give an error, but it prints a garbage value. So we cannot call it a declaration. But as per the syntax it is a declaration. So what is the difference in this case?

3
  • 1
    "If it is a declaration, the printf() statement should give an error" - what error are you talking about specifically? Aug 17, 2014 at 14:26
  • Note that even if a were only declared, not defined, the printf() statement would compile — a declaration makes the variable or function available for use. If the variable were only declared and not defined, then the code would not link (and hence would not run) until the code was modified to include a definition of the declared variable. For example, int main(void) { extern int a; printf("%d\n", a); return 0; } int a = 57; shows a declaration and a subsequent definition. Aug 17, 2014 at 14:27
  • Unrelated to your question,but you should use return 0 just before } or you might encounter a warning
    – Spikatrix
    Aug 17, 2014 at 14:29

4 Answers 4

4

There's no way around the fact that this is a declaration. Every definition in C language is a declaration at the same time. In the reverse direction: some declarations are definitions and some are not.

int a; in your code is a declaration that happens to be a definition as well.

2

When you declare a local variable in c, space on the stack is created for the variable. When you declare int a without giving a a specific value, it's value will be whatever is already in memory in the location set aside for it on the stack. That is most likely a garbage value, which is why you're seeing strange numbers when printing the value of a. To avoid this, declare int a = 0, or some other number.

As for how to declare rather than define a varaible, you should use the extern keyword as explained in the other answer.

2

It's a definition.

For a variable in C, you'd have to use the 'extern' keyword if you wanted to only declare it, not define it. A good article can be found here

1
  • 1
    As for the "garbage value", that's because you didn't initialize it.
    – magdalar
    Aug 17, 2014 at 14:06
-1

Declaration means we are just creating a variable or method. Defination means we are assigning some value for a variable & doing some functions in method

1
  • 1
    You don't create anything with a declaration. You just tell the compiler there will be an item that will be created later.
    – harper
    Aug 17, 2014 at 16:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.