+ 1

about default value of int variables? cpp

hi guys hope you are doing well! im curious about default integer variable values and i tried to do an experiment on it. i realized variables get some values when a certain action is executed (eg you print it or use it in a loop) tho the experiment is fun (atleast for me) any of you experts have any additional info About it or does your compiler behave like sololearns compiler? perhaps do this experiment yourself and reply if something fun happened. heres the link to my experiment https://code.sololearn.com/cvCXOfw4ClQ3/?ref=app thanks guys have fun!

26th Nov 2018, 9:42 AM
sina
sina - avatar
7 ответов
+ 6
Using uninitialized variables lead to undefined behavior. There's no such thing as default value without explicit initialization. So those numbers have no meaning at all and in different compiler yield different random values. never count on them! ______ https://en.wikipedia.org/wiki/Undefined_behavior
26th Nov 2018, 9:53 AM
Babak
Babak - avatar
+ 6
I call this 'unintended effects'. True, even you as a coder can do this. I once keyed in 'O' capital o instead of '0' zero or zypher. It took me days before I spotted my own error!!!
29th Nov 2018, 9:55 PM
Da2
Da2 - avatar
+ 5
"I'm curious about what does more complex functions would do with an undefined variable." For the most part, the compiler during the compilation phase issues warnings if there are any uninitialized variables in the codebase. If you, for any reason, ignore them, the garbage value — the value of an uninitialized variable — ripple through each module which utilizes those variables and as a result "silently" produces the wrong result. So, the saying "safe better than sorry" would be applied nicely to this context by making sure to give proper init value to each and every variable.
26th Nov 2018, 10:19 AM
Babak
Babak - avatar
+ 5
Most curious thing about garbage values is that you can generate a hard to find bug. Imagine that you have not initialized some position or acessed some no valid memory. Now imagine that when you are debugging the garbage value sometimes assumes a number that you expected. You can pass a lot of time without knowing what is going on.
26th Nov 2018, 11:34 AM
Anya
Anya - avatar
+ 5
Parameter passing between functions is normal. My own functions often return default values which, to my mind, is a good practice. Whenever you use functions from someone else, fool around with it first. That way, you'll discover 'unintended effects' such as values generated ex. int x = xfunc().
29th Nov 2018, 10:04 PM
Da2
Da2 - avatar
+ 1
exactly thats what intrigued me in the first place. it can cause a flaw in code if you keep a variable uninitialized . im curious about what does more complex functions would do with an uninitialized variable.
26th Nov 2018, 9:58 AM
sina
sina - avatar
0
Anya that sounds like a serious hard time :l
26th Nov 2018, 12:05 PM
sina
sina - avatar