Should Local Variable Initialisation Be Mandatory?

前端 未结 17 2491
忘掉有多难
忘掉有多难 2021-02-14 01:26

The maintenance problems that uninitialised locals cause (particularly pointers) will be obvious to anyone who has done a bit of c/c++ maintenance or enhancement, but I still se

17条回答
  •  情歌与酒
    2021-02-14 02:27

    In C/C++ I totally agree with you.

    In Perl when I create a variable it is automatically put to a default value.

    my ($val1, $val2, $val3, $val4);
    print $val1, "\n";
    print $val1 + 1, "\n";
    print $val2 + 2, "\n";
    print $val3 = $val3 . 'Hello, SO!', "\n";
    print ++$val4 +4, "\n";
    

    They are all set to undef initially. Undef is a false value, and a place holder. Due to the dynamic typing if I add a number to it, it assumes that my variable is a number and replaces undef with the eqivilent false value 0. If i do string operations a false version of a string is an empty string, and that gets automatically substituted.

    [jeremy@localhost Code]$ ./undef.pl
    
    1
    2
    Hello, SO!
    5
    

    So for Perl at least declare early and don't worry. Especially as most programs have many variables. You use less lines and it looks cleaner without explicit initializing.

     my($x, $y, $z);
    

    :-)

     my $x = 0;
     my $y = 0;
     my $z = 0;
    

提交回复
热议问题