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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    "If it is a declaration, the printf() statement should give an error" - what error are you talking about specifically? – AnT stands with Russia Aug 17 '14 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. – Jonathan Leffler Aug 17 '14 at 14:27
  • Unrelated to your question,but you should use `return 0` just before `}` or you might encounter a warning – Spikatrix Aug 17 '14 at 14:29

4 Answers4

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
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

Sagar Sakre
  • 2,336
  • 22
  • 31
magdalar
  • 131
  • 1
  • 2
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.

Alex Kleiman
  • 709
  • 5
  • 14
-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

novice ad
  • 1
  • 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 '14 at 16:58