int main()
{
int a,b, c, p, x, x1, d;
int nr=0;
cin>>a>>b>>c>>x;
x=x1;
while (x1>0)
{
p = x1 / 10;
x1 = p;
nr++;
}
d = 0;
if ((a > 1 && a < 9) && (0 < b && b < 10) && (0 < c && c < 10))
{
if (a==nr)
{
d = d + 1;
}
if (x/10==b)
{
d = d + 1;
}
if (x%10==c)
{
d = d + 1;
} }
if (d==3)
cout<<"DA";
else
cout<<"NU";
cout<<d;
return 0;
}
ok i found out that the mistake was i initialized the x = x1 instead of x1 = x, as x1 had no value what so ever..but it still tells me d == 2, the "if x/10==b" condition doesn t work, any suggestions?
It is UB, although in practical terms I'm yet to find a compiler that did anything other than simply read whatever happens to be in that memory like any other int. Some of them can be encouraged to warn about it. It would be nice if they did something spectacular instead.
#include <iostream>
void f(int x)
{
int a;
std::cout << "a is "<< a << "\n";
if (x == 0)
{
a = 1;
std::cout << "a is set to 1\n";
}
std::cout << "a is " << a << "\n\n";
}
int main()
{
for (int i : {0, 1})
{
f(i);
}
}
When I compile and run the above program with GCC 7.3 using the -O2 optimization flag I get the following output.
a is 0
a is set to 1
a is 1
a is 0
a is 1
In the second case (f(1)) it looks like the value of a magically changed without being set.
You can make compiler-catchable uninitialized variable warnings be errors in gcc as well, I don't think that was really the point (yes, VS's project defaults are more convenient).
I totally agree it is better to make uninitialized variables be compiler errors when possible, but the point he was showing was that uninitialized variables can cause more than just a variable to be assigned -393745 instead of an actual value (the UB actually changed the apparent runtime logic of the program, halfway through the program).
I know one can manually change the warning levels. I just noticed when using the default levels there is a difference in how two different compilers handle uninitialized variables.
An interesting bit of trivia how different implementations vary in small details. Nothing more.
Yeah, I actually did get a warning. The purpose of the program was just to give a counterexample to what Repeater said, and hopefully convince people to not rely on UB.
after meditating a bit yesterday i found the mistakes by myself, thanks for telling me about debugging, and about the "not known" value of a variable that uninitialized.
Thank you all guys for taking your time to help me out! :)