This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the difference between a definition and a declaration?
I am trying to thoroughly understand "defining" and "declaring" in C.
I believe x here is defined, since external variables are automatically initialized to 0, and something that's declared and initialized is defined. Is that accurate?
int x;
main() {}
According to one x in this case is a definition, but why? It is not being initialized...
int print_hello()
{
int x;
}
Declaring is telling the compiler that there's a variable out there that looks like this.
Defining is telling the compiler that this is a variable.
One refers to the existence of a thing, the other is the thing.
In your example, the scope is what makes the difference. Declarations are made in a file scope, but in a block scope it is not possible to declare anything; therefore, the second example is a definition; because, there is nothing left to do with the int x;.
That makes the first example (in the file scope) a declaration that some int x; exists. To covert it from a declaration, you need to specify that a value is assigned to it, forcing the memory allocation. Like so: int x = 0;
C and C++ are very scope sensitive when it is analyzing constructs.
"Define" does not mean "initialized." It means something is created, rather than just referenced.
A definition allocates but does not necessarily initialize memory. This can lead to fun debugging.
Declaration introduces a name in a TU. Definition instantiates/allocates storage for that name.
int x; //definition,also a declaration. Every definition is a declaration.
int main(){}
Related
This question already has answers here:
How do I use extern to share variables between source files?
(19 answers)
Closed 3 years ago.
There is a code snippet as below,
int var1;
extern int var2;
It is a multiple choice.
The answer is, First statement declares and defines var1, but second statement only declares var2.
But I think it is supposed to be "Both statements only declare variables, don’t define them."
Which one is correct?
This might help. source
Declaration of a variable is for informing to the compiler the
following information: name of the variable, type of value it holds
and the initial value if any it takes. i.e., declaration gives details
about the properties of a variable. Whereas, Definition of a variable
says where the variable gets stored. i.e., memory for the variable is
allocated during the definition of the variable.
In C language definition and declaration for a variable takes place at
the same time. i.e. there is no difference between declaration and
definition. For example, consider the following declaration
int a;
Here, the information such as the variable name: a, and data type:
int, which is sent to the compiler which will be stored in the data
structure known as symbol table. Along with this, a memory of size 2
bytes(depending upon the type of compiler) will be allocated.
Suppose, if we want to only declare variables and not to define it
i.e. we do not want to allocate memory, then the following declaration
can be used
extern int a;
In this example, only the information about the variable is sent and
no memory allocation is done. The above information tells the compiler
that the variable a is declared now while memory for it will be
defined later in the same file or in different file.
The answer depends on several factors.
If these declarations
int var1;
extern int var2;
are block scope declarations then the first declaration is also a definition and the second declaration is just a declaration without a definition. The variable var1 is not initialized that is it has an indeterminate value.
If these declarations are declarations of the file scope then whether the first declaration is a definition is defined by whether the declaration has an external definition.
If the declaration does not have an external definition then this declaration named as tentative definition is a definition and have an implicit initializer equal to 0.
As for the second declaration then again whether it is a definition depends on whether there is an external definition or not. If there is no external definition then the linker can either create the definition or issue an error.
In C a declaration with the file scope is also a definition when either it has an initializer or it is a tentative definition without an external definition.
Actually, the extern keyword extends the visibility of the C variables and C functions.
Declaring vs Defining a variable?
Declaration of a variable/function simply declares that the variable/function exists somewhere in the program but the memory is not allocated for them.
Snippet 1:
extern int var;
int main(void)
{
var = 10;
return 0;
}
Snippet 1 throws an error in compilation. Because var is declared but not defined anywhere. Essentially, the var isn’t allocated any memory. And the program is trying to change the value to 10 of a variable that doesn’t exist at all.
Snippet 2:
#include "somefile.h"
extern int var;
int main(void)
{
var = 10;
return 0;
}
Supposing that "somefile.h" has the definition of var. Snippet 2 will be compiled successfully.
This question already has answers here:
Error "initializer element is not constant" when trying to initialize variable with const
(8 answers)
Closed 6 years ago.
What I thought static pointer is like other static variables, ones initialised with an value it have same value till end, like that the same address will be held in the static pointer. But in this case the compiler is throwing error
//initialiser element is not constant static int *a = &b[0];
#include <stdio.h>
int main(void)
{
int b[2];
static int *a = &b[0]; // removing static the program works well.
printf("%u",a);
a = &b[1];
printf("%u",a);
return 0;
}
So what is the use of static pointer?
In C, your code doesn't make sense. b has automatic storage duration so conceptually will have a different address each time main is encountered. The static will be initialised only once, and on subsequent invocations of main it may well point to something invalid.
But, and this is the interesting bit, in C++ it ought to make sense since you are not allowed to call main yourself: the behaviour on your doing so is undefined. So the inference of this is that the compiler ought to know that the static is valid for the lifetime of main, and compile the code! Perhaps there is something in the C++ Standard that explicitly forbids this.
In C you are allowed to call main recursively (even implicitly recursively), so the compiler ought to emit an error.
You have two options. Add static to int b[2], or remove it from int *a.
The address of b isn't static. It's variable, because b is a variable with automatic storage.
There may be confusion about static vs const.
Const variables will keep the same value from the time they are initialized until they go out of scope, unless const_cast<> is used, though as #Bathsheba mentioned in comment, use of const_cast<> on a variable declared const is undefined.
Static means it will get initialized at the spot first reaches but then not go out of scope until the end of program execution.
This question already has answers here:
What is the difference between a definition and a declaration?
(27 answers)
Closed 8 years ago.
#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?
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.
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.
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
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
#include <stdio.h>
int main()
{
extern int a;
extern int a;
int a = 10;
return 0;
}
what is the problem with this code? Since multiple declaration is allowed in c what is the problem with this code
The problem with the code is that the compiler is first informed that a is a global variable (due to the extern keyword); and then a is defined as a local 'automatic' variable. Hence there is a conflict in the defined scope of a
As an alternative to automatic variables, it is possible to define variables that are external to all functions, that is, variables that can be accessed by name by any function. (This mechanism is rather like Fortran COMMON or Pascal variables declared in the outermost block.) Because external variables are globally accessible, they can be used instead of argument lists to communicate data between functions. Furthermore, because external variables remain in existence permanently, rather than appearing and disappearing as functions are called and exited, they retain their values even after the functions that set them have returned. —The C Programming Language
An external variable must be defined, exactly once, outside of any function; this sets aside storage for it. The variable must also be declared in each function that wants to access it; this states the type of the variable. The declaration may be an explicit extern statement or may be implicit from context. ... You should note that we are using the words definition and declaration carefully when we refer to external variables in this section. Definition refers to the place where the variable is created or assigned storage; declaration refers to places where the nature of the variable is stated but no storage is allocated. —The C Programming Language
From your question I observe that you are visualizing your program something like this
#include <stdio.h>
int main()
{
extern int a; //declaration
extern int a; //declaration
int a = 10; //declaration + definiton
return 0;
}
With above understanding of extern keyword. Your question is obvious.
Let us understand use extern of keyword thoroughly.
Extern variable declaration is a promise to the compiler that there would be a definition of a global variable some place else. Read This. In other words extern keyword tell the compiler that forget about this variable at the moment and left it to linker to link it with its definition. That is extern variables are actually linked to its definition by linker. Moreover Local variables have no linkage at all. So while searching for its definition compiler found a definition without linkage. Thats the error.
As a rule of thumb just remember when you declare any variable as extern inside any function then you can only define it outside of that function.(However there is no use of it).
I've faced three separate situations in C lately that I would assistance on:
My C code has a global variable:
int ref_buf; //declared in a header file
In a function definition I use the same name as a parameter:
void fun(int ref_buf, param2, param3)
{
}
Will it overwrite the originally defined global variable and will it cause bugs?
Can I declare a static variable in a C data structure like so?:
struct my
{
int a;
static int b;
};
Does it work? Is there any specific situation where one would need it?
Can I initialize a individual structure variable as follows:
struct my
{
int a;
int b = 4;
};
Question 1
All references to ref_buf in that function will bind to the parameter and not the global variable.
Question 2
This is not legal in C but is legal in C++. The keyword static in C can only be used on file scope variables or on locals.
Question 3
No this is not legal in C (or C++). You will need to create a factory method to handle this.
my create_my() {
my m;
m.b = 4;
return m;
}
On Q3: GCC allows you to initialize a struct like this (as required by the C99 standard):
struct
{
int a;
int b;
} my = { .b = 4 };
GCC doc on designated initializers
1a) The local and global variables are separate entities, and so the local one won't overwrite the global. However, the global one won't be accessible inside the function (see also notes below).
1b) It not actually incorrect, but it is guaranteed to cause confusion, and confusion causes bugs, so it's best to use different names for each.
2) No, that's not legal C. You can however make the whole struct static.
3) No. You do it like this:
struct my
{
int a;
int b;
} = {0, 4};
Note 1: Variables should be declared in .c files, not .h files. If you need to make a variable accessible in multiple files, put an extern declaration in the header file.
Note 2: Avoid global variables if at all possible.
Question 1:
I think the variable declared in the local scope takes precidence, it shouldn't overwrite it but in the scope that the variable is declared it will be used instead.
That is assuming that it compiles.
On Q1:
Do not declare variables in a header file. If you include that header file in two source files and compile the source files together, you've got problems. Maybe your linker will get you out of them, maybe not.
If you really need global variables, and this happens a lot less than typical beginners think, put something like extern int ref_buf; in the header file, and int ref_buf; in a source file. That means there is one ref_buf, and all other source files will be able to find it.
The function parameter is essentially a new variable with the same name, and all references in the function will be to it. You will not be able to access the global variable from within that function. The function creates an inner scope, and variables declared in an inner scope are different from those in an outer one. This is potentially confusing, and makes it easy to create bugs, so having variables of the same name and different scopes is generally discouraged. (Variables of the same name in different struct definitions are usually not confusing, since you have to specify what struct contains the variable.)
The compiler will compile the function, but a good compiler will issue a warning message. If it refuses to compile because of one variable shadowing another of the same name, it isn't a real C compiler.
1) Local variables always take precedence e.g.
int ref = 10;
void fun(int ref)
{
printf("\n%d\n", ref);
}
int main()
{
fun(252);
return 0;
}
shows: 252
Qs 2 and 3 won't work in C.
Yes, it will technically overwrite, but a good compiler will warn you about this situation, and you will have "warnings = errors" on when you compile, so this won't actually compile.
Not needed, since the "my" struct is already declared as static, and it is therefore declared for the entire struct. This allocates the memory for the entire struct, so there is no need to say "take part of the struct which is already static and make it static".
No, not in the definition, but you can when you create an "instance", something like:
struct my MY =
{
{0, 4}
};