By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,984 Members | 1,057 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,984 IT Pros & Developers. It's quick & easy.

declaration and definitions

P: 48
Expand|Select|Wrap|Line Numbers
  1. int a;
The above snippet is a declaration. Whether it is a definition too.....
Because one website that i referred tells that only
Expand|Select|Wrap|Line Numbers
  1. extern int i;
is a declaration.
All the other types are both declaration and definition.
Is it true?
If yes kindly clarify when a variable is declared and when the same is defined?
Thanks in advance.......
Aug 27 '10 #1

✓ answered by weaknessforcats

A variable is defined when it occupies memory.

Otherwise, it is declared.

Therefore:

1) int i; is a definition. The variable i is created and occupies memory.

2) extern int i; is a declaration. The variable i is an int but is is not in this source file. That is, it is defined in some ther file with external linkage.

3) extern int i = 10; is a definition. A variable i is reated with a value of 10. The variable is to be accessible from other files that use extern int i;

Based on (3), you can define variables that are accessible from other files that use extern. This is important for const variables which are by default not accessible from other files by using extern. That is you define your const variable with external linkage:

extern const int i = 10;

Now other files can access this variable by using:

extern const int i;

Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
A variable is defined when it occupies memory.

Otherwise, it is declared.

Therefore:

1) int i; is a definition. The variable i is created and occupies memory.

2) extern int i; is a declaration. The variable i is an int but is is not in this source file. That is, it is defined in some ther file with external linkage.

3) extern int i = 10; is a definition. A variable i is reated with a value of 10. The variable is to be accessible from other files that use extern int i;

Based on (3), you can define variables that are accessible from other files that use extern. This is important for const variables which are by default not accessible from other files by using extern. That is you define your const variable with external linkage:

extern const int i = 10;

Now other files can access this variable by using:

extern const int i;
Aug 27 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.