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– Ricardo Pontual
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 themain
?– Isac
@Isac at the beginning of each
{...}
.– user72726