c declaration and initialization - c

Is it fine to declare a global variable as auto.
for example
auto int i;
static int j;
int main()
{
...
return 0;
}

Why haven't you tried compiling the code snippet in your question? If you had, you would know by now that it gives a compiler error. In gcc:
foo.c:3: error: file-scope declaration of 'x' specifies 'auto'
So I guess the answer tyo your question is "no, it's not fine".

The meaning of 'auto' in C is simply a variable that is a local variable.
So it is totally contradictory to say you would like to declare a global variable as a local variable.
I think you are talking about having a localised global. If you would like to declare a variable that is local to the .c file you are working in, and you don't want it to be accessible outside the c file, but you would like for it to be accessible by all functions in that file, you should declare it as a static variable, like you have done for the variable j.
Therefore you would have something like the following in example.c:
static int i; //localised global within the file example.c
static int j; //not accessible outside the .c file, but accessible by all functions within this file
int main()
{
//do something with i or j here.
i = 0 ;
j = 1 ;
}
void checkFunction()
{
//you can also access j here.
j = j+ 5;
}
I guess I should add that there are multiple ways you to use the keyword static for a variable.
The one that you might be familiar with is:
1) Declaring a variable static within a function - this ensures the variable retains its value between
function invocations.
The second one ...
2) Declaring a variable as static within a module (or a .c file) - this is what I have described
above. This ensures a variable is localised within that module or .c file, but it is global so that
it can be used by any of the functions defined in that particular file. Hence the name localised
global.
However, it will not be accessible outside that .c file.

Based on this explanation of auto:
http://msdn.microsoft.com/en-us/library/6k3ybftz%28VS.80%29.aspx
It says that auto variables are scope-limited, and their address is not constant. Since globals have neither of these properties, it wouldn't make sense for a global to be auto.

No, it is not possible. The reason is that global variables are in a specific data segment (along with static variables declared inside the functions) initialized to zero all at once before main() is called.

Related

When using Static storage class, is stack used for Function implmentation? If yes, how does it work? If no, what is used? [duplicate]

I've seen the word static used in different places in C code; is this like a static function/class in C# (where the implementation is shared across objects)?
A static variable inside a function keeps its value between invocations.
A static global variable or a function is "seen" only in the file it's declared in
(1) is the more foreign topic if you're a newbie, so here's an example:
#include <stdio.h>
void foo()
{
int a = 10;
static int sa = 10;
a += 5;
sa += 5;
printf("a = %d, sa = %d\n", a, sa);
}
int main()
{
int i;
for (i = 0; i < 10; ++i)
foo();
}
This prints:
a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60
This is useful for cases where a function needs to keep some state between invocations, and you don't want to use global variables. Beware, however, this feature should be used very sparingly - it makes your code not thread-safe and harder to understand.
(2) Is used widely as an "access control" feature. If you have a .c file implementing some functionality, it usually exposes only a few "public" functions to users. The rest of its functions should be made static, so that the user won't be able to access them. This is encapsulation, a good practice.
Quoting Wikipedia:
In the C programming language, static
is used with global variables and
functions to set their scope to the
containing file. In local variables,
static is used to store the variable
in the statically allocated memory
instead of the automatically allocated
memory. While the language does not
dictate the implementation of either
type of memory, statically allocated
memory is typically reserved in data
segment of the program at compile
time, while the automatically
allocated memory is normally
implemented as a transient call stack.
And to answer your second question, it's not like in C#.
In C++, however, static is also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.
There is one more use not covered here, and that is as part of an array type declaration as an argument to a function:
int someFunction(char arg[static 10])
{
...
}
In this context, this specifies that arguments passed to this function must be an array of type char with at least 10 elements in it. For more info see my question here.
Short answer ... it depends.
Static defined local variables do not lose their value between function calls. In other words they are global variables, but scoped to the local function they are defined in.
Static global variables are not visible outside of the C file they are defined in.
Static functions are not visible outside of the C file they are defined in.
Multi-file variable scope example
Here I illustrate how static affects the scope of function definitions across multiple files.
a.c
#include <stdio.h>
/*
Undefined behavior: already defined in main.
Binutils 2.24 gives an error and refuses to link.
https://stackoverflow.com/questions/27667277/why-does-borland-compile-with-multiple-definitions-of-same-object-in-different-c
*/
/*int i = 0;*/
/* Works in GCC as an extension: https://stackoverflow.com/a/3692486/895245 */
/*int i;*/
/* OK: extern. Will use the one in main. */
extern int i;
/* OK: only visible to this file. */
static int si = 0;
void a() {
i++;
si++;
puts("a()");
printf("i = %d\n", i);
printf("si = %d\n", si);
puts("");
}
main.c
#include <stdio.h>
int i = 0;
static int si = 0;
void a();
void m() {
i++;
si++;
puts("m()");
printf("i = %d\n", i);
printf("si = %d\n", si);
puts("");
}
int main() {
m();
m();
a();
a();
return 0;
}
GitHub upstream.
Compile and run:
gcc -c a.c -o a.o
gcc -c main.c -o main.o
gcc -o main main.o a.o
Output:
m()
i = 1
si = 1
m()
i = 2
si = 2
a()
i = 3
si = 1
a()
i = 4
si = 2
Interpretation
there are two separate variables for si, one for each file
there is a single shared variable for i
As usual, the smaller the scope, the better, so always declare variables static if you can.
In C programming, files are often used to represent "classes", and static variables represent private static members of the class.
What standards say about it
C99 N1256 draft 6.7.1 "Storage-class specifiers" says that static is a "storage-class specifier".
6.2.2/3 "Linkages of identifiers" says static implies internal linkage:
If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.
and 6.2.2/2 says that internal linkage behaves like in our example:
In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function.
where "translation unit is a source file after preprocessing.
How GCC implements it for ELF (Linux)?
With the STB_LOCAL binding.
If we compile:
int i = 0;
static int si = 0;
and disassemble the symbol table with:
readelf -s main.o
the output contains:
Num: Value Size Type Bind Vis Ndx Name
5: 0000000000000004 4 OBJECT LOCAL DEFAULT 4 si
10: 0000000000000000 4 OBJECT GLOBAL DEFAULT 4 i
so the binding is the only significant difference between them. Value is just their offset into the .bss section, so we expect it to differ.
STB_LOCAL is documented on the ELF spec at http://www.sco.com/developers/gabi/2003-12-17/ch4.symtab.html:
STB_LOCAL Local symbols are not visible outside the object file containing their definition. Local symbols of the same name may exist in multiple files without interfering with each other
which makes it a perfect choice to represent static.
Variables without static are STB_GLOBAL, and the spec says:
When the link editor combines several relocatable object files, it does not allow multiple definitions of STB_GLOBAL symbols with the same name.
which is coherent with the link errors on multiple non static definitions.
If we crank up the optimization with -O3, the si symbol is removed entirely from the symbol table: it cannot be used from outside anyways. TODO why keep static variables on the symbol table at all when there is no optimization? Can they be used for anything? Maybe for debugging.
See also
analogous for static functions: https://stackoverflow.com/a/30319812/895245
compare static with extern, which does "the opposite": How do I use extern to share variables between source files?
C++ anonymous namespaces
In C++, you might want to use anonymous namespaces instead of static, which achieves a similar effect, but further hides type definitions: Unnamed/anonymous namespaces vs. static functions
It depends:
int foo()
{
static int x;
return ++x;
}
The function would return 1, 2, 3, etc. --- the variable is not on the stack.
a.c:
static int foo()
{
}
It means that this function has scope only in this file. So a.c and b.c can have different foo()s, and foo is not exposed to shared objects. So if you defined foo in a.c you couldn't access it from b.c or from any other places.
In most C libraries all "private" functions are static and most "public" are not.
People keep saying that 'static' in C has two meanings. I offer an alternate way of viewing it that gives it a single meaning:
Applying 'static' to an item forces that item to have two properties: (a) It is not visible outside the current scope; (b) It is persistent.
The reason it seems to have two meanings is that, in C, every item to which 'static' may be applied already has one of these two properties, so it seems as if that particular usage only involves the other.
For example, consider variables. Variables declared outside of functions already have persistence (in the data segment), so applying 'static' can only make them not visible outside the current scope (compilation unit). Contrariwise, variables declared inside of functions already have non-visibility outside the current scope (function), so applying 'static' can only make them persistent.
Applying 'static' to functions is just like applying it to global variables - code is necessarily persistent (at least within the language), so only visibility can be altered.
NOTE: These comments only apply to C. In C++, applying 'static' to class methods is truly giving the keyword a different meaning. Similarly for the C99 array-argument extension.
static means different things in different contexts.
You can declare a static variable in a C function. This variable is only visible in the function however it behaves like a global in that it is only initialized once and it retains its value. In this example, everytime you call foo() it will print an increasing number. The static variable is initialized only once.
void foo ()
{
static int i = 0;
printf("%d", i); i++
}
Another use of static is when you implement a function or global variable in a .c file but don't want its symbol to be visible outside of the .obj generated by the file. e.g.
static void foo() { ... }
From Wikipedia:
In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.
I hate to answer an old question, but I don't think anybody has mentioned how K&R explain it in section A4.1 of "The C Programming Language".
In short, the word static is used with two meanings:
Static is one of the two storage classes (the other being
automatic). A static object keeps its value between invocations. The objects declared outside all blocks are always static and cannot be made automatic.
But, when the static keyword (big emphasis on it being used in
code as a keyword) is used with a declaration, it gives that object internal linkage so it can only be used within that translation unit. But if the keyword is used in a function, it changes the storage class of the object (the object would only be visible within that function anyway). The opposite of static is the extern keyword, which gives an object external linkage.
Peter Van Der Linden gives these two meanings in "Expert C Programming":
Inside a function, retains its value between calls.
At the function level, visible only in this file.
If you declare a variable in a function static, its value will not be stored on the function call stack and will still be available when you call the function again.
If you declare a global variable static, its scope will be restricted to within the file in which you declared it. This is slightly safer than a regular global which can be read and modified throughout your entire program.
A static variable is a special variable that you can use in a function, and it saves the data between calls, and it does not delete it between calls. For example:
void func(void) {
static int count; // If you don't declare its value, it is initialized with zero
printf("%d, ", count);
++count;
}
int main(void) {
while(true) {
func();
}
return 0;
}
The output:
0, 1, 2, 3, 4, 5, ...
In C, static has two meanings, depending on scope of its use. In the global scope, when an object is declared at the file level, it means that that object is only visible within that file.
At any other scope it declares an object that will retain its value between the different times that the particular scope is entered. For example, if an int is delcared within a procedure:
void procedure(void)
{
static int i = 0;
i++;
}
the value of 'i' is initialized to zero on the first call to the procedure, and the value is retained each subsequent time the procedure is called. if 'i' were printed it would output a sequence of 0, 1, 2, 3, ...
If you declare this in a mytest.c file:
static int my_variable;
Then this variable can only be seen from this file. The variable cannot be exported anywhere else.
If you declare inside a function the value of the variable will keep its value each time the function is called.
A static function cannot be exported from outside the file. So in a *.c file, you are hiding the functions and the variables if you declare them static.
Share what I learned about this point.
In C static is a declaration specifier, which falls into three categories:
storage classes: there are four classes: auto, static, extern and register.
type qualifiers: like keywords: const, volatile, etc.
type specifiers: like keywords: void, char, short, int, etc.
So static is a storage classes. It will determine the following three properties of each variable in a C program.
storage duration: means when memory is allocated for the variable and when the memory is released. A variable with static storage duration stays at the same memory location as long as the program is running.
scope: means the portion of the program text in which the variable can be accessed. A static variable has a file scope instead of a block scope.
linkage: means the extent to which the variable can be shared by different parts(or files) of a program. If a static variable is declared inside a block then it has no linkage. If a static variable is declared outside blocks, then it has internal linkage. Internal linkage makes it accessible in a single file.
The static storage class has a different effect on a variable depending on it is declared outside a block or inside a block. Need to consider case by case.
It is important to note that static variables in functions get initialized at the first entry into that function and persist even after their call has been finished; in case of recursive functions the static variable gets initialized only once and persists as well over all recursive calls and even after the call of the function has been finished.
If the variable has been created outside a function, it means that the programmer is only able to use the variable in the source-file the variable has been declared.
Static variables in C have the lifetime of the program.
If defined in a function, they have local scope, i.e. they can be accessed only inside those functions. The value of static variables is preserved between function calls.
For example:
void function()
{
static int var = 1;
var++;
printf("%d", var);
}
int main()
{
function(); // Call 1
function(); // Call 2
}
In the above program, var is stored in the data segment. Its lifetime is the whole C program.
After function call 1, var becomes 2. After function call 2, var becomes 3.
The value of var is not destroyed between functions calls.
If var had between non static and local variable, it would be stored in the stack segment in the C program. Since the stack frame of the function is destroyed after the function returns, the value of var is also destroyed.
Initialized static variables are stored in the data segment of the C program whereas uninitialized ones are stored in the BSS segment.
Another information about static: If a variable is global and static, it has the life time of the C program, but it has file scope. It is visible only in that file.
To try this:
file1.c
static int x;
int main()
{
printf("Accessing in same file%d", x):
}
file2.c
extern int x;
func()
{
printf("accessing in different file %d",x); // Not allowed, x has the file scope of file1.c
}
run gcc -c file1.c
gcc -c file2.c
Now try to link them using:
gcc -o output file1.o file2.o
It would give a linker error as x has the file scope of file1.c and the linker would not be able to resolve the reference to variable x used in file2.c.
References:
http://en.wikipedia.org/wiki/Translation_unit_(programming)
http://en.wikipedia.org/wiki/Call_stack
A static variable value persists between different function calls andits scope is limited to the local block
a static var always initializes with value 0
There are 2 cases:
(1) Local variables declared static: Allocated in data segment instead of stack. Its value retains when you call the function again.
(2) Global variables or functions declared static: Invisible outside compilation unit (i.e. are local symbols in symbol table during linking).
Static variables have a property of preserving their value even after they are out of their scope!Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.
Look at this for example -
A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over.
#include<stdio.h>
int fun()
{
static int count = 0;
count++;
return count;
}
int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}
This will output: 1 2
As 1 stays in the memory as it was declared static
Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage. See this for more details.
#include <stdio.h>
int main()
{
static int x;
int y;
printf("%d \n %d", x, y);
}
This will output : 0
[some_garbage_value]
These are the major ones I found that weren't explained above for a newbie!
In C programming, static is a reserved keyword which controls both lifetime as well as visibility. If we declare a variable as static inside a function then it will only visible throughout that function. In this usage, this static variable's lifetime will start when a function call and it will destroy after the execution of that function. you can see the following example:
#include<stdio.h>
int counterFunction()
{
static int count = 0;
count++;
return count;
}
int main()
{
printf("First Counter Output = %d\n", counterFunction());
printf("Second Counter Output = %d ", counterFunction());
return 0;
}
Above program will give us this Output:
First Counter Output = 1
Second Counter Output = 1
Because as soon as we call the function it will initialize the count = 0. And while we execute the counterFunction it will destroy the count variable.

Access of static variable from one file to another file

I recently came across the question like how to access a variable which declared static in file1.c to another file2.c?
Is it possible to access static variable?
My understanding about static keyword in C is,
static is "internal linkage", so they are accessible only from one compilation unit - the one where they were defined. Objects declared with internal linkage are private to single module.
As one of my friend suggest me below solution.
In file1.c
#include <stdio.h>
int main()
{
int b=foo();
printf("%d",b);
return 0;
}
in file2.c
static int a=25;
int foo()
{
return a;
}
compiled by gcc file1.c file2.c -o file
If I do above I can access the variable.
So my questions are:
Does the above program violate static variable rules?
If not, why is this so, and is there any other way to access static variable except including file (#include <…>) not like this.
How am I able to access a static variable from another file?
In C, how do I restrict the scope of a global variable to the file in which it's declared?
Correct me if I'm wrong with static variable concept and if any better solutions are available to access static variable?
1) does the above program violate static variable rules?
No you are not vailoting any rules. Here foo function create copy of value of that static variable and used in other file. Its fine.
2) If not why is this so, and is there any other way to access static variable except including file (#include<>) not like this How am I able to access a static variable from another file?
Static variable are only mean to use in that file only.
You can not use that variable making them extern in other files.
Another dirty hack is to get pointer of that static variable and make that as global pointer and making that as extern in another file you can use that static variable.
file1.c
#include<stdio.h>
static int a=25;
int* ptr = &a;
file2.c
#include<stdio.h>
extern int *ptr;
int main()
{
printf("%d",*ptr);
return 0;
}
Correct me if I'm wrong with static variable concept and if any better solutions are available?
A static variable has a lifetime extends across the entire run of the program
If you do not initialize static variable with some value then its default value would be 0.
A static variable has scope limited to its file only. You can not access it by name from a different file.
You have temp1.c and temp2.c both are getting compiled together then also you can have static variable of same name in both files — and they are separate variables.
In C, how do I restrict the scope of a global variable to the file in which it's declared?
By making that global variable as static.
What we commonly call a variable in C is actually two things: an object, the memory allocated for the variable interpreted with a certain type, and an identifier, one way to access that object.
There is no problem in accessing a static object or its value from another compilation unit. Your function foo promotes the value to another unit, that is fine, but it could even promote the address of a without problems.
Having internal linkage only concerns the identifer, the name a. This one is only visible inside file2.c.
With the static int a=25; the variable a will have internal linkage; meaning the linker cannot see a anywhere outside of the file2.c TU.
When you're calling foo() in file2.c, you get a copy of a, it's the copy that you print; but this doesn't mean you have access to the actual a defined in file2.c When you need such an access where the same variable is visible across different TUs, you could do this
Defining file
This file both declares and defines the variable; additionally initializes it to 1 too, without which it'll be default initialized to 0.
// (non-static) global variable with external linkage and thus visible across TUs
int var_across = 0;
void use()
{
var_across = 1;
}
Using file
// just a declaration to tell that it's defined elsewhere; not a definition
extern int var_across;
void use_here()
{
var_across = 2;
}
Assigning address of static variable to pointer will make static variable available to subfiles.
In subfiles we have to use extern keyword to the pointer.
But it is not necessary to do that.

Use of 'extern' Keyword [duplicate]

This question already has answers here:
How do I use extern to share variables between source files?
(19 answers)
Closed 9 years ago.
i am confused in the use of extern keyword in C. when it is used with a variable, then it means the declaration of variable. I declare the variable tmp outside the main() function and define it in a separate block in main but when i print the value in subsequent block i got an error "UNRESOLVED EXTERNAL LINK". I am confused please give me detailed explanation.
#include <stdio.h>
extern int tmp ;
int main()
{
{
int tmp = 50;
}
{
printf("%d",tmp);
}
return 0;
}
No; extern int tmp; means "somewhere else there is a definition of the variable tmp"; this is a declaration — you can reference tmp but it is not defined. Further, when you write extern int tmp; outside a function, it means that the variable will be defined outside a function — it is a global variable which may be defined elsewhere in the current source file or in another source file. (The rules for extern int tmp; written inside a function are moderately complex; let's not go there now!)
Your local variable int tmp = 50; in the function is unrelated to the global variable tmp declared outside. The local variable hides the global variable inside the braces. (The local variable is also unused.) The printf() statement, though, references the global variable; the local variable is not in scope for the printf().
Because you do not define the global variable (for example, by adding int tmp = -2; at the bottom of the file), your program fails to link and will continue to do so until you either define the variable in this source file or link in another source file where the variable is defined.
This line :
extern int tmp ;
says look for the tmp variable definition elsewhere , which means look for the variable definition in other translation unit in the entire program.
when you define int tmp in main it is local to that function, i.e it doesn't have any external linkage.
Disclaimer- There are seriously many posts on SO regarding this like the one with link provided in the comments above . No, matter how much I add to this it will end up being a repetition. however , you have a good answer below by Jonathan leffler too.
Extern is redeclaration
, so it doesn't crate variable, but only tells compiler that real declaration is somewhere else.
You can use it in one source file to refer to variable declaration in another file, or in the same file to express that you use previously declared global variable.
So when you declare global variable
int a=5;
and use in function in the same source file, you can add extern int a; in the body of a function to clearly tell that it uses global variable but declaration is not here.
type func(arguments){
extern int a;
.
.
.
And when int a=5 is in another source file you place
extern int a;
in source file you actually want to use global variable a declared in previous source file.
This is about linkage. When you declare a variable extern you give it external linking, saying it's defined with global linkage somewhere else.
In your function you're defining a variable called tmp, but it doesn't have global linkage, it's a local variable. You'd have to define it outside of any function to give it global linkage.
There's also static linkage, which means a variable is global but only to the current compilation unit (source file).
Using the extern keyword you only declare the symbol tmp. Which means the symbols is defined somewhere else and will be resolved at link time.
So if you do not provide a compiled object defining the symbol, the linker gives you some kind of "unresolved symbol" error.
See the following question for more details on Declaration or Definition in C

Incrementing a global static int in main

Here's my code:
File DataTypes.h
static int count=0;
File TreeOps.h
#include"DataTypes.h"
void printTree(Tree* ptr)
File TreeOps.c
#include"TreeOps.h"
void printTree(pointer){
count++; // incrementing the count;
printf("%d",counter);
}
File TreeMain.c
#include"TreeOps.h"
printTree(pointer); // all the necessary declarations are done.
printf("%d",count);
If in printTree function the printf gives count=1; while in main function it gives me 0.
Why?
static variable in this context means: every c file has its own variable instance. Remove static definition in h-file:
extern int count;
and add this to one of c files:
int count = 0;
extern means: this is forward declaration. By defining a variable as extern, you tell to compiler that count has int type, and this variable is created somewhere. Actually, this variable is created in one and only one c file. You can use it in any c file where DataTypes.h is included. In the file where this variable is created, compiler uses it. In all other file this variable becomes external reference, which is resolved later by linker.
First off, defining data or functions in header files is a bad practice in C programming. In DataTypes.h you don't just declare the count variable, but you define it.
What actually happens is that the count is defined separately in each translation unit and you end up with two variables after linking. The linker doesn't merge them because they are marked static, that means they should be local to the translation unit.
If you want the count variable to be shared between the TreeOps.c and TreeMain.c translation units, you must use extern in the header file which only declares it:
extern int count;
And then define it globally as int count in either of TreeOps.c or TreeMain.c.
You don't have a "global static int" in your program. Entities declared as static cannot possibly be "global". The whole point of declaring something static is to make it local to a specific translation unit. This is exactly what you've done: you have declared two completely independent static variables in two different translation units. Each variable is local to its own translation unit. Then you are modifying one of these variables and printing the other. No wonder that the other remains unchanged.
In this case you have to decide what it is exactly you want. You can either have your variable as a global variable or as a static variable, but not both at the same time. "Global variable" and "static variable" are mutually exclusive concepts. So, what is it you want: global or static?

C variables scope in struct

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}
};

Resources