Variable declaration assignment in C

Asked

Viewed 234 times

4

Is it necessary to assign a value to a variable in C once we declare it? I ask because an old programmer told me that it is necessary, because, if we do not declare at first, the compiler could assign any random value to it. Follow the statement following the guidance of senior Programmer:

int num = 0;

According to it it has to be this way whenever it is to declare a variable. My question is: Is this really necessary? My compiler does not generate this random number as it says. And if necessary, how do I go about character type variables? This way wouldn’t be for old compilers?

Note: It uses turbo C. It is 70 years old and every day program. It is a legend.

  • It is not necessary to assign value to the variable immediately after declaring it.However, we must always assign a value to the variable before it is used. For example, you can declare the variable at the beginning of your code, and only assign value immediately before using the variable.

2 answers

6


It is necessary to assign a value to a variable in C once we declare it?

No, that made less sense in older compilers than it does now. The first C compilers required declaring the variable at the beginning of the function before it had any real execution, so if it had to assign a value in the statement there would be an execution (processing cost) that right there in the front would be despised and its value replaced by another in a new assignment, which is inefficient and against the philosophy of C, so assigning value in the statement was in large part disincentive cases.

Over time compilers were able to understand declaration only at the time that the variable is needed, and this is already in the language specification since 1999, so any compiler that doesn’t meet a specification 20 years ago is a rotten compiler and shouldn’t even be considered C anymore.

Unfortunately some people teach programming this way, either because they can not do different than what they learned, only follow cake recipe, or because they believe in the myth that has compiler that does not accept this form (yes, it does, but again it cannot be considered C and most codes will never be compiled by a compiler like this, and the solution to the case if it is necessary to compile this code in a outdated compiler is to use a tool that processes this code before passing to the compiler, so it does not force the code to be worse by an exception (unless it is no exception, have to look at the concrete case), but people do not usually behave like engineers and do not seek appropriate solutions, just follow the flow of someone who had a bad idea one day).

But still in modern compilers it may have some less common case that the statement must be made before its value is assigned and still worth the philosophy of maximum efficiency, therefore C does not require assigning a value in the statement. A typical example is if this variable will receive an external data entry, where there will clearly be an assignment, then why assign a value that will be dropped before its use? This applies to any function that will receive the variable as a parameter by reference only to fill it. And there may be other cases.

The experienced programmer who told you this is right for modern compilers in most cases, but maybe he didn’t say it the right way, or you didn’t quite understand what he said. You should always assign a value to the variable before using it. It does not need to be in the statement, but at some point between the statement and the first access to that value, it may even be in the statement itself, and today in the overwhelming majority of cases it is the ideal place to do this (read one of the most important exceptions in the previous paragraph).

If you fail at this, you’ll access junk that’s in your memory, and the worst that can happen to you is to work, because you’ll think you’re right. Some cases the garbage may be exactly what you expect and look right, but in other cases it will not be so. C is probably the language of "high level" where this maxim is worth more:

Fiat 147 todo detonado andando pelas ruas

One way to prevent this from happening is to assign it right away in the declaration, but do not do so with a single general rule. It’s standard behavior until you have a reason to do it differently.

If you add this as a cake recipe you are learning wrong, if you understand the real motivation and then make a decision depending on the specific case you are making, then you have become a real programmer. And if you improve that skill and always look for creative and sensible solutions to problems you will become an engineer.

My compiler does not generate this random number as it says

It worries me, need to understand what is this "random" in order to make correct decisions (see comment below).

This form would not be for old compilers?

As I said, no, on the contrary, in old compilers it made even more sense that today not assign values during the declaration in most cases.

And if necessary, as I do for character type variables?

Just like other guys, there’s no difference:

char c = 'x';

Helped? I guess not because it depends on the context. There are several reasons to do it one way or another.

Now without declaring and makes sense (here is context):

char c;
scanf("%c", c);

Has a example with context.

You want to do it like string?

char texto[] = "teste";

An example of absurd attribution in unnecessarily declaration:

FILE *fp = NULL;
//mais código aqui
fp = fopen("Emails.txt", "rt");

I put in the Github for future reference.

Only one thing is worse than this, is to have no code between the declaration and the actual initialization. Not by performance, but because it makes no sense to leave in separate lines by no criteria.

See more in:

  • Random number: According to his logic, if I declare a variable and do not assign an initial value to it, and if I print it, the output would be any number. As far as I know, and so in my compiler, the output is 0. But according to him the output could be any integer number "chosen randomly" by the compiler. In practice I have seen that this does not occur. I just wanted to know if this occurred in the first days of language.

  • 3

    The number is not random, it’s just undetermined, there’s nothing random, let alone chosen by the compiler, alias, the compiler has zero influence on it. It will be a number that is in memory at that moment in the position where that variable refers in that execution. It has more to do with the operating system, and on some architectures under some settings has great chance in a very basic example that the value is the same as that which ended in the last execution of this code, if it is called soon after. Anything random.

0

This is how it is recommended that you initialize the variables with some value to not take risks... In c numeric variables with 0 are usually initialized but sometimes it takes a random number of RAM to initialize this variable

For variables of the char type they function differently from the numeric ones they are not necessary to initialize because they create memory allocations according to the size that assigns them

For example:

char var[10];

In this example the char variable will occupy the space of 10 characters they always carry an escape character at the end to know when the string ends

But in case you do:

var[]="Fulano";

it will only occupy 7 characters (6 of the word John Doe plus 1 of the escape character 0) [No need to put the escape character]

And in this case the variable will be equivalent to:

char var[7] = "Fulano";

But since we do not declare the variable with 7 but with 10 carcteres the rest of the characters are filled with NULL

I hope I answered your question :)

Browser other questions tagged

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