Why do you usually declare a variable with default value?

Asked

Viewed 2,688 times

38

In several applications that have been written with strongly typed languages, a variable (usually) is declared with its default value.

Example:

int x = 0;
double y = 0;

However, it is possible to declare them without defining an initial value.

In this way:

int x;
double y;

In the case I asked my teacher, and he replied that long ago, if it was not stated in the first way, an absurd number would be assigned to the variable n, y.

  • Is this premise true? If so, what is this number?

  • The example I demonstrated was based on the language C#, but I believe that the declaration of variables should be similar in other languages. This also occurs/occurred in other languages?

  • 2

    It is common for them to initialize them with the value 0 so that they can add up dpois values. For example, you want to count how many times your program ran, you initialize the variable count with the value 0 and dpois uses count++ for each time it rotates

  • 1

    Depending on the language, the compiler will take place to define a value to these variables, it can have a very large random range, and because of this it is necessary to initialize the variables. Can at the end contain "trash" in memory, you initialize them to remove this "trash".

  • 1

    @Francis You are taking into account that the author is talking more about accountants, which in the case is not. But also this right.

  • Relevant for the study: https://stackoverflow.com/a/6032889/2263584

  • Declaration <> initialization, often we may not initialize mainly when we are talking about POO’s. And that of assigning an absurd number I think is not quite so, because otherwise it could create a virus and exhaust all PC resources by just declaring variables

  • an absurd number would be assigned to the variable, that would be, Integer.maxvalue something of the kind?

  • 1

    @Everson formerly in certain languages had junk memory and actually happened today, mainly in C# this does not happen, and I think that in a general way does not have the right, but rather the occasion ... depends.

  • 2

    @Uzmkartanis is as there have been some comments, it depends on the language in C# it does not happen is a premise of languages, already in others it can happen the garbage of memory, and the correct way is in charge of each language ... !!!

  • 3

    They came back as broad do not believe it is, because having a reference language is easy to say whether or not it is attribution factor right in creation .

  • Downvoter, if you don’t know how to vote you can read here en.stackoverflow.com/help/privileges/vote-up and here also en.stackoverflow.com/help/privileges/vote-down

  • If you can’t read at all, or don’t want to read at least leave a comment instead of doing one more random downvote, explaining how I can improve my response and contribute to the community.

  • As far as I know, C-based languages still have this behavior when defining a variable it does not clear the memory address that will be used to store the variable’s data. Although more current languages already do this automatically is still considered a good practice of programming always initialize the variables.

Show 7 more comments

2 answers

42


General

In some languages there is no initialization, is the case of C, there have to do manual. In C there is a raw access to memory and if the programmer does not take care of the initialization takes what is in memory, ie, dirt, what was dropped by application that had that reserved area, or even the same application since there is a virtual memory system. That used to be true and it’s true today.

It’s not a question of taking an absurd number, you can take exactly what you want. Only you have no control if you let language do that. It can change with each execution. I don’t even know if we can say it’s totally random.

In C++ it’s like that too. In Assembly even more. It almost stops there. But C++ has constructors and some variables will always be initialized.

In C# it is not true. Worth before and worth today. There is that from time ago, there is how technology works.

I take this opportunity to make it clear that this has to do with static typing and strong non-trying. People confuse a lot in typing style.

C#

C# is a language with managed memory. This means that it does not allow, even by specification, that any state of memory is invalid or of dubious value. The specific mechanisms of how to obtain this management are specified more or less in open.

All objects in C# are allocated with some default value, there is not the slightest chance that a memory allocation will allow access before all your data is initialized. In general this initialization occurs by a builder.

Types by reference

Types by reference have two parts, one that will be in the heap and will be initialized by a constructor. Even if you have not declared one, even if it does not initialize all members, the compiler will insert initialized code from all of them into your code.

A variable containing the reference, the second part, shall be initialized with null (pointer to 0) always. There is no chance of having another value there, unless explicitly your code puts something else. Then do:

object x = null;

is absolutely unnecessary. Some use it because they think it’s more readable. I don’t think so. I always think that any information placed that is inambígua and that should be known by the programmer does not help in readability.

I don’t particularly like to let an object be null, for me this concept would not even exist in language (in fact in recent versions can turn it off), so I would always initialize an object by reference, but if I had to initialize with the null and in the current form of the language has case that is useful, I would only declare the variable leaving the implicit initialization even.

Of course any operation you attempt to perform later may require that it is not null or that the null be declared explicitly to avoid a bug unexpected. By sheer compiler ease it can inform you that an operation will possibly result in error, so it may require you to be explicit to show him that you are aware that the value should be null. But changes nothing semantically. It is not a requirement to ensure valid state of memory.

Types per value

Types by values have allocation at the same location of the variable and also need to be initialized. The initialization is always by the value 0 of it, that is, all bits are filled with 0, as well as in the type by reference. If no value is set it is 0 that will be adopted. Then do:

int x = 0;

is unnecessary, other than by taste.

That’s the same as doing:

int x = new Int32();

Note that there is no non-zero default value on any object. What exists is non-zero constructed value.

This is not a primitive thing of language, but some may have different values. It is possible to have a default constructor provided by the compiler. See:

DateTime x;

Has value 1/1/0001 00:00:00, it would be an invalid date.

GC couldn’t have known that, there’s no way he’s responsible for that.

This is done by the compiler. It’s not that there is no initialization, it exists, only that it is implicit. There are cases that are implicit in consumption, but it is explicit within the type.

Choose to be explicit or not, where gives, is taste, does not change performance or semantics.

I put in the Github for future reference.

Garbage Collector

Nothing has to do with the garbage collector, has to do with memory management and is guaranteed independent of GC. It is not GC that does this boot. Initialization will always occur by construction, even if it is delegated to a mechanism of the Runtime, which is not GC. GC handles allocation.

Understand that the construction of the object has two phases, the allocation, made by GC and the initialization made by code placed by the compiler or by Jitter.

Completion

All this applies to class or instance variables as well. The question does not say whether they are local variables, but it does not matter. Of course there are small differences between local, class and instance initialization.

And that goes for C, not for the CLR. The cleanliness of stack is configurable. And in heap only the build will reset, also depends on how the compiler issues the code.

  • @bigown a very simple example the variable g has not been initialized ! http://ideone.com/qkQjvn ie it needs to be initialized with NULL

  • Ah, @Virgilionovic , now I understand what you meant. Yes, variables local need to be initialized via constructor or reference pass - a behavior different from, say, members of a class.

  • @Virgilionovic Yes, if you will make use that requires a null, is true, but not that the statement is necessary, is that the later use requires, so much so that the error does not occur in the statement. It is a different requirement. What is being talked about here is about being the statement.I edited.

  • Trying to use a variable that was not initialized with a default value returns the error Use of unassigned local variable 'variable' in C#. If you define int variable = 0 the error adds up.

17

When you create a variable, you are allocating a placeholder in memory.

What happens is that in some programming languages like C allocates the space in memory but does not clear the contents of that space.

Example: created int exp; in C. Now the variable exists! But the space allocated to it may have already been used in some situation. So it can happen of its variable exp have an integer value = 1238643485 (demonstrative value).

By creating a variable as follows int exp = 0; you create the variable, and declare an initial value 0 that will replace whatever value was previously used in that allocation. This way you will always know the exact value of that variable.

Declaring a variable already assigning a certain value helps in controlling counters that we use numerous times in our applications.

Memory Allocation in C#

But there are also languages that you will not have problems with values already used before in certain allocation, example C#.

This is because there is a certain function called Garbage Collector (GC) that is responsible for managing and allocating memory in your application. You find a little more about this here.

  • 5

    I missed saying something about C# as !!! I think it would look perfect.

  • 7

    Speaking of C# itself, the idea of initializing a variable goes to another path. It is impossible to use a variable that was not initialized in C#. That is, this must be the real reason he sees codes that already initialize the variable with zero.

  • 1

    When a C application is closed without wiping the memory, its variables are still occupying space in the computer’s memory?

  • In C#, when initializing any primitive type it assigns the default value to the variable, in the case of int is 0, just as bool is false, etc. If the variable is Nullable, then the default value becomes null in the case of a declaration of type int? x;

  • 1

    @Francis does not occupy memory, but the data remains there until it is written over.

  • 2

    @Grupocdsinformática This is not true, local variables are not initialized. Open a console and test.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.