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?

4
  • This is very vague. I don't undertand the question very well. Commented Oct 25, 2010 at 7:57
  • Also, this code might give you a segfault depending on what platform you are running it on. Commented Oct 25, 2010 at 7:58
  • 6
    @krico: The question is precise. Commented Oct 25, 2010 at 7:59
  • 1
    Use the conversion character "%p" to print pointers that you cast to (void*), otherwise casting a pointer to an integer type might lead to undefined behavior. (If you really can't avoid, cast pointers to uintptr_t, if it exists) Commented Oct 25, 2010 at 16:41

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

2

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

8 Comments

As he's just taking the address of the variable, I don't see why this is UB.
@Job, oh, sorry, didn't see that
@Armen Tsirunyan I'm trying to show that the compiler allocates memory for int x;
@R.. No, this isn't an unitialized pointer. This is well defined because we have an uninitialized variable and are just taking its address
Use the conversion character "%p" to print pointers that you cast to (void*).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.