views:

73

answers:

2
int x;

Is this declaration or 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 a declaration. So is it a definition ?

+2  A: 

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

Armen Tsirunyan
As he's just taking the address of the variable, I don't see why this is UB.
Job
@Job, oh, sorry, didn't see that
Armen Tsirunyan
@Armen Tsirunyan I'm trying to show that the compiler allocates memory for int x;
Parixit
It is UB to use an uninitialized pointer in any context, even without dereferencing it, if I remember correctly.
R..
@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
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
@Armen: of course you're right. I misread the code.
R..
Yes it might be undefined behavior to convert an address to an integer, if the address does not fit: "Except as previously specified, theresult 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 integertype."
Jens Gustedt
Use the conversion character "%p" to print pointers that you cast to `(void*)`.
Jens Gustedt
@Jens Gustedt thnx for "%p"..
Parixit
+1  A: 

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