In C, declare variables in the middle of a code block can cause the program to behave indefinitely?

3

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

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

Then in C, declare variables in the middle of code blocks, can they cause the program to behave indefinitely?

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

    
asked by anonymous 04.06.2018 / 12:21

1 answer

6

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

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

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

It also used to perform very large functions which could be lost in what you were doing, but this argument is still fragile.

Your problem solved coincidentally. Maybe because the variables were declared in the wrong places. Or you're using an absurdly bad compiler, but I doubt there's such an atrocity. Coincidence solutions are not good. If the solution was to remove the variables from the function, it caused more problems there, not seeing them does not mean that it is not there.

It is not that there will be undefined behavior, it is to declare where you should not change the algorithm.

We can not help much because we do not even know what it's all about. A function that does nothing and causes side effects is just looking at the wrong problem, it is impossible to do this.

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

    
04.06.2018 / 18:44