3
int x;

Is this a declaration or a definition?

As I write the following code,

#include <stdio.h>

int main(void)
{
    int x;
    printf("%p",&x);
    return 0;
}

it prints some address. So as memory is allocated, int x; can't be just a declaration. So is it a definition?

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
Parikshita
  • 1,297
  • 5
  • 15
  • 23

2 Answers2

3

From the C standard (n1256):

6.7 Declarations
...
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;101)
— for an enumeration constant or typedef name, is the (only) declaration of the identifier.

In this case, int x; is a definition (or a defining declaration).

John Bode
  • 119,563
  • 19
  • 122
  • 198
2

int x; is a definition. extern int x; is just a declaration. extern int x = 3; is also a definition. HTH

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • 3
    As he's just taking the address of the variable, I don't see why this is UB. – mtvec Oct 25 '10 at 08:01
  • @Job, oh, sorry, didn't see that – Armen Tsirunyan Oct 25 '10 at 08:02
  • @Armen Tsirunyan I'm trying to show that the compiler allocates memory for int x; – Parikshita Oct 25 '10 at 08:02
  • It is UB to use an uninitialized pointer in any context, even without dereferencing it, if I remember correctly. – R.. GitHub STOP HELPING ICE Oct 25 '10 at 08:14
  • 3
    @R.. No, this isn't an unitialized pointer. This is well defined because we have an uninitialized variable and are just taking its address – Armen Tsirunyan Oct 25 '10 at 08:15
  • It isn't an uninitialised pointer, just an uninitialised variable but that is still undefined behaviour. One reason is that - though not very common now - parity protected memory may be being used so that a hardware exception can be raised to signal certain types of memory errors (e.g. bits changed by cosmic rays). Where parity protection is used it is quite common to have to write to a location first to set the parity correctly before doing a read. – Dipstick Oct 25 '10 at 08:27
  • Yes it might be undefined behavior to convert an address to an integer, if the address does not fit: "Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type." – Jens Gustedt Oct 25 '10 at 16:32
  • 1
    Use the conversion character "%p" to print pointers that you cast to `(void*)`. – Jens Gustedt Oct 25 '10 at 16:34