In C, does initialising a variable to it\'s own value make sense? If yes, what for?
Allow me to elaborate. In Git sources there are some examples of initialising a varia
This compiles because Standard C99 §6.2.1/7 says:
Any identifier that is not a structure, union, or enumeration tag "has scope that begins just after the completion of its declarator." The declarator is followed by the initializer.
However, value of status
is Indeterminate. And you cannot rely on it being initialized to something meaningful.
How does it work?
int status
creates an space for the variable to exist on the stack(local storage) which is then further read to perform status = status
, status
might get initialized to any value that was present in the stack frame.
How can you guard against such self Initialization?
gcc provides a specific setting to detect self Initializations and report them as errors:
-Werror=uninitialized -Winit-self
Why is it used in this code?
The only reason I can think it is being used in the said code is to suppress the unused variable warning for ex: In transport.c
, if the control never goes inside the while
loop then in that control flow cmp
will be unused and the compiler must be generating a warning for it. Same scenario seems to be with status
variable in wt-status.c
For me the only reason of such self-assigning initialization is to avoid a warning.
In the case of your transport.c
, I don't even understand why it is useful. I would have left cmp
uninitialized.
My own habit (at least in C) is to initialize all the variables, usually to 0. The compiler will optimize unneeded initialization, and having all variables initialized makes debugging easier.
There is a case when I want a variable to remain uninitialized, and I might self-assign it: random seeds:
unsigned myseed = myseed;
srand(myseed);
I think status = status
doesn't change the value of status
(compared to int status;
). I think it is used to suppress the unused variable
warning.
On MacOS X 10.7.2, I tried this example - with the result shown...
$ cat x3.c
#include <stdio.h>
int status = -7;
int main()
{
printf("status = %d\n", status);
int status = status;
printf("status = %d\n", status);
return 0;
}
$ make x3
gcc -O -std=c99 -Wall -Wextra x3.c -o x3
$ ./x3
status = -7
status = 1787486824
$
The stack space where the local status
in main()
has been used by printf()
so the self-initialization copies garbage around.