+ 1

Why initialize a variable?

When I'm writing snippets in C++, I frequently declare with int x; or something, then later assign or cin.get a value. Now sometimes I read: No, you should initialize a variable always and immediately, so that it doesn't contain random stuff. No real reason is given. Also sometimes I read there was a huge difference between initialization and assignment, where in my mind it should be the same, only that before the first assignment there's still stuff at that place that's been marked as overwriteable. So... why's it any different? Now when I think about writing a large code that is fragmentarized into .cpps, .hpps etc., I'd declare my stuff separately as you then do; would I really set everything to 0, 0.0, "", {} or whatever just to assign other values later anyway? What is your opinion about it? Why is it better to initialize?

13th Oct 2018, 2:50 PM
HonFu
HonFu - avatar
3 odpowiedzi
+ 4
TL;DR Just initialize your variables. It's good practice. If you don't initialize your variables, it will give you something random. Sometimes you won't even realize if your code has a problem because of it. An example is if you want to test a variable with a given value. You don't really know if it's initialized or not. You can keep your variables uninitialized. But it's good practice to initialize them. There's no reason to not initialize anyway. I mean, it's just a little more typing. Nowadays compilers can give you a warning if a variable is uninitialized. You can also see if a variable is initialized or not by debugging. But I still would recommend to initialize variables so you could avoid doing this. As for initialization vs assignment, they're not completely different. Assignment is when you assign a variable to a value (a = 42). Initialization is like assignment but it happens when the variable is declared (int a = 42).
13th Oct 2018, 3:33 PM
qwerty
qwerty - avatar
+ 3
Bebida Roja You allocate memory for a variable when you declare it. Initializing writes in the space already allocated.
13th Oct 2018, 5:43 PM
Emerson Prado
Emerson Prado - avatar
- 1
to make space for it in memory
13th Oct 2018, 3:22 PM
Bebida Roja
Bebida Roja - avatar