initialization - C++ : how to make sure all variables are initialized? -


recently had lots of trouble non initialized variable.

in java, default value of variable null, therefore exception thrown when if non-initialized variable used. if understood, in c++, variable initialized whatever data turns out in memory. means program run, , might hard know there wrong it.

what clean way deal ? there programming habit reduce risk ? in case, variable declared in header file , should have been initialized in cpp file, example of things makes error more likely.

thx


edition after receiving few answers:

my apologies, question not specific enough.

the answer use flag compilers informed of non-initialized variables useful.

but there rare cased variables can not initialized @ beginning, because depending on behavior of system.

in header file

double learnedvalue; 

in cpp file

/* code has nothing learnedvalue ... */  learnedvalue = a*b*c; // values of a, b , c computed in code above  /*code making use of learned value ... */ 

now happened forgot line "learnedvalue=a*b*c".

but program working good, value of learnedvalue initialized whatever in memory when declared.

in java, such error not issue, because code making use of learned value crash or throw exception (at least know wrong).

in c++, can apparently happy , never know there problem @ all. or ?

pls make sure have appropriate warning levels set while compiling program. compilers issue appropriate warning whenever un-initialized variables used.

on g++, -wall compiler option show warnings.

on visual studio, might have use warning level 4.

also, there static code analysis tool available in market. cppcheck 1 such tool available free.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -