Does this code do anything?
int *n;
while (n!=0)
{
n = &n;
}
Does this code do anything?
int *n;
while (n!=0)
{
n = &n;
}
It's undefined behavior for several reasons, so who knows.
n
before initialization.int **
value to a int *
variable.So it might trigger the Singularity... but only on your machine.
No this does nothing particularly useful. It program will execute in 1 of 2 ways that I can see
The local n
is initialized to a nonzero value by chance. It will then enter an infinite loop where the stack address of the local is assigned to the local. This won't terminate
The local n
is initialized to 0
by chance and the loop will not execute.
That's not even a valid C program. From the spec, section 6.5.5 Cast operators, paragraph 3:
Conversions that involve pointers...shall be specified by means of an explicit cast.
It will have an indeterminate behavior since the n
variable is not initialized. If this is also corrected, it will either go in an infinite loop (if n
is initialized to a non null value) or it will do nothing.
It doesn't compile. If you insert a cast to make it compile. BTW, you assign a int**
to an int*
and the compiler will probably emit a warning for such code.
Note: When n
is initialized, clang
is smart enough to optimize the code to either a nop
if it is initialized to 0 or to an infinite loop otherwise.
It stores an constant if type int ** into a variable of type int*. Uhm... It will probably loop forever, since it's unlikely that &n == 0. And, oh, the first time the content of "n" is undefined!
First of all, you have an assignment from incompatible pointer type (you're trying to assign an int **
to an int *
); I don't remember exactly if it should trigger an error or just a warning (in C most probably a warning, in C++ it may be an error).
Then, even if you put there a cast (n=(int *)&n
), that code exhibits undefined behavior, since at the very first iteration you're reading an uninitialized variable. Probably nothing very bad would happen (after all you're not dereferencing that pointer), but it's undefined whether the loop would be executed, as a rule of thumb, if that region of stack has already been used n
will be nonzero, otherwise it will probably be zero.
If, correcting all mistakes/UB, it were:
int *n=NULL;
while (n!=0)
{
n = (int *) &n;
}
it would perform an iteration, since it starts at NULL
(which is guaranteed to be 0), and then it would exit from the loop, since no valid pointer compares equal to 0 (again, this is guaranteed by the standard).
As far as usefulness is concerned: as it is, for a "real" application it's completely useless.
Depends on the initial value of n
, but most likely goes into an infinite loop.
n
is a local (stack) variable that is a pointer to int.n
contains a non-zero value (e.g., is not NULL
)
n
to the address of n
(pretty much guaranteed to be non-zero)