Is not it necessary to initialize an accumulator?

4

Ando with this question, I would like to know why it is not necessary to initialize an accumulator in vb.net

Module Module1

Sub Main()
    Dim valor, suma As Integer

    Do
        Console.Write("Ingrese valor (0 pera finalizar):")
        valor = Integer.Parse(Console.ReadLine())

        suma = suma + valor
    Loop While valor <> 0

    Console.WriteLine(suma)

    Console.ReadKey()
End Sub

End Module

In other languages like C or C # they ask you to assign / initialize with a value but in VB.Net it does not seem necessary. Why?

    
asked by Popplar 29.03.2017 в 08:58
source

2 answers

3

Well, in C # you have to differentiate between "Fields" and "Local Variables". The fields do not need to be initialized, while the local variables do. We see it in an example:

class Prueba
{
    int i; //Al estar definido en la clase, es un Campo

    public Prueba()
    {
        i+=1; 
    }
}

This example compiles perfectly, and i is initialized with the default value of int , or 0

However, the following example does not compile:

class Prueba
{
    public Prueba()
    {
        int i; //Al estar definido en un método, es una variable local
        i+=1; 
    }
}

This is done to ensure the reliability of the application, and is perfectly explained in the C # language reference in the 5.3 Definitive Assignment

Regarding VB.Net, it is a language that has inherited certain habits of the original Visual Basic, among them the need not to initialize the local variables. It is a language in which it is somewhat easier to shoot yourself in the foot, and for that reason it is recommended to activate the options Option Strict and Option Explicit , to prevent problems difficult to debug.

Summing up: Why is it like that? Because when both languages were defined, it was decided that it should be like that, it is not necessary to give it many more laps. C # is a new language that has learned from errors of previous languages, while VB.net had to make some concessions to make the transition from Visual Basic easier.

    
answered by 29.03.2017 / 10:23
source
3

Very simple: all types have a default value with which they are initialized if a specific value is not indicated when declaring them.

In the specific case of Integer , said value is 0 .

    
answered by 29.03.2017 в 09:19