Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this self-assignment do something sensible?

Tags:

c++

c

I just found this line of code within a function, which puzzles me. Can this make sense in any context or it is undefined behavior?

char * acFilename = acFilename;

EDIT: The compiler complains with Warning C4700, that I am using an uninitialized variable.

like image 728
Fabian Avatar asked Feb 21 '17 11:02

Fabian


3 Answers

At block scope, in C++, this is undefined behaviour, as the right-hand side reads the variable the variable before it has been initialized (C++14 [dcl.init]/12).

At block scope, in C11, this could either be undefined behaviour or behave as an uninitialized variable, depending on various details of the implementation and the rest of the function, see here for detailed analysis.

At namespace scope, in C++, it is OK well-defined and makes a null pointer. This is because all static variables are zero-initialized before their initializers are considered. (C++14 [basic.start.init]/2).

At file scope in C, it is a constraint violation; static variables must have a constant expression as initializer, and the value of a variable cannot be a constant expression.

like image 114
M.M Avatar answered Sep 21 '22 15:09

M.M


No this code does not make any sense. It's probably a typo, maybe somebody meant to use

char* acFilename = ::acFilename; 

or

char* acFilename = m_acFilename; 

or something else.

As it stands, it's confusing and unhelpful at best, probably a bug because somebody meant to use a different variable.

like image 31
nvoigt Avatar answered Sep 21 '22 15:09

nvoigt


I've seen this before. Since gcc is quite trigger happy with its uninitialized variable warnings this is a trick to silence those warnings. Not sure if it's intentional design choice by gcc or the compiler just being stupid, but I've seen people do this on purpose to make gcc shut up (and in the process break the warning that might be correct in the future).

I would just replace it with an initialization to NULL. This is a bad habit, doesn't work on other compilers and a NULL can't be less correct than an indeterminate value and undefined behavior.

Just to demonstrate how this works (and also because I wanted to know if newer gcc versions still do this):

$ cat foo.c
int
foobar(void)
{
    int foo;
    return foo + foo;
}
$ cc -c -Wall -O2 foo.c
foo.c: In function ‘foobar’:
foo.c:6:13: warning: ‘foo’ is used uninitialized in this function [-Wuninitialized]
  return foo + foo;
         ~~~~^~~~~
$ ed foo.c
[...]
$ cc -c -Wall -O2 foo.c
$ cat foo.c
int
foobar(void)
{
    int foo = foo;
    return foo + foo;
}
$ cc -c -Wall -O2 foo.c
$ cc -v
[...]
gcc version 6.2.0 20161005 (Ubuntu 6.2.0-5ubuntu12)
$
like image 43
Art Avatar answered Sep 25 '22 15:09

Art