In C, can declaring variables in the middle of a block of code lead the program to undefined behavior?

Asked

Viewed 474 times

3

I have read in several books that in C variables should be declared at the beginning of a code block. But what happens if I declare them in the middle?

I was doing a program in c that shows a text in a window created only using the X11 library. It had a function - split(...) -, that inexplicably, each time I wore it, the text appeared in random colors. Hence decides to move all variables of the program to the beginning of each block. And the problem is gone.

Then in C, declaring the variables in the middle of the code blocks can lead the program to undefined behavior?

But I’m not entirely sure that this was the cause of my problem. Link to question about my problem.

  • There is no such requirement, a variable must be declared (and initialized depending on the case) before it is used, but it is not necessary to declare everything at the beginning. A variable for a counter in a loop for does not need to be declared at the beginning for example

  • What do you mean by "at the beginning of a code block" ? At the beginning of a function ? At the beginning of the main ? Before the main ?

  • @Isac at the beginning of each {...}.

1 answer

6


These books are old or very bad. There is a lot of material that repeats cake recipes without understanding why, and end up talking nonsense.

Declaring variables closer to where they are used is the best that can be done.

In the past compilers did not allow this, it complicated their lives. Some still do not allow, but run from them.

It also used to do very large functions which could get lost in what it was doing, but this argument is still fragile.

The solution to your problem was coincident. Perhaps because the variables were declared in the wrong places. Or he’s using an absurdly bad compiler, but I doubt there’s such an atrocity. Coincidental solutions are not good. If the solution was to take the variables out of the function, then it caused even more problem, the fact of not seeing them does not mean that it is not there.

It’s not that there will be undefined behavior, it’s that declaring where you shouldn’t can change the algorithm.

We can’t help much because we don’t even know what it is. A function that does nothing and causes side effects is just to look at the wrong problem, it is impossible to happen this.

What is undefined behavior, unspecified and defined by the implementation?

Fiat 147 detonado circulando pelas ruas

  • 2

    This brand image of yours is the ultimate :D, and curiously always appropriate to the subject addressed.

  • In fact, it’s not because of where I declared the variables. The problem has reappeared, and now I don’t even know what to do.

Browser other questions tagged

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