uninitialised variable but NO error

G

geek.arnuld

this is the programme: [1]

#include <iostream> // std::cout

int main()
{
int sum;
std::cout << sum << "\n";
}


when i compile it using gcc 4.1.2, i get this:

----------------------------------------------------------------------------
[unix@arch cpp]$ g++ first.cpp -o first
[unix@arch cpp]$ ./first
sum is: -1208774992
[unix@arch cpp]$
-----------------------------------------------------------------------------


i think the programme is wrong BUT why this does not give any error
like "uninitialised variable"?





[1] http://home.no.net/dubjai/win32cpptut/html/w32cpptut_01_02_02.html
 
M

Mike Wahler

this is the programme: [1]

#include <iostream> // std::cout

int main()
{
int sum;
std::cout << sum << "\n";
}


when i compile it using gcc 4.1.2, i get this:

----------------------------------------------------------------------------
[unix@arch cpp]$ g++ first.cpp -o first
[unix@arch cpp]$ ./first
sum is: -1208774992
[unix@arch cpp]$

It does not because your code does not violate any language rules.
However, when you execute it, it will produce 'undefined
behavior' (even if it 'appears to work OK').
like "uninitialised variable"?

Some compilers can and do issue a 'warning' about this,
but there's no language requirement that one must.

Also, if your compiler can warn about this, it's possible
that you'll need to configure it to do so. Check your
documentation.

-Mike
 
R

Rolf Magnus

this is the programme: [1]

#include <iostream> // std::cout

int main()
{
int sum;
std::cout << sum << "\n";
}


when i compile it using gcc 4.1.2, i get this:

----------------------------------------------------------------------------
[unix@arch cpp]$ g++ first.cpp -o first
[unix@arch cpp]$ ./first
sum is: -1208774992
[unix@arch cpp]$
-----------------------------------------------------------------------------


i think the programme is wrong BUT why this does not give any error
like "uninitialised variable"?

Because it doesn't violate the syntax rules of C++. It just invokes
undefined behavior. GCC can issue a warning in such a case, but only if you
enable optimizations (because only then it will do a more extensive code
flow analysis). To get a warning, add "-Wuninitialized -O" to the command
line options of g++.
As a minimum for the warning flags, you should add to the g++ command
line: "-ansi -pedantic -Wall -Wextra" (-Wall includes -Wuninitialized).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top