I have a small problem converting code from java to C++
I am trying to check if a 2d array is set ,this is my java code
for(int area_y = y -1 ;area_y > 0 ;area_y--)
{
for(int area_x = 0 ;area_x < x; area_x++)
{
if(area[area_x][area_y] == 0)
{
System.out.print(" "); // this is printed
// if area[area_x][area_y] is not set
}
else
System.out.print(area[area_x][area_y]);
}
System.out.println();
}
and this is my c++ code and this works
for(int area_y = y -1 ;area_y > 0 ;area_y--)
{
for(int area_x = 0 ;area_x < x; area_x++)
{
if(area[area_x][area_y] == 0) // this line does not work as
// the next line is not executed
{
cout << "1";
}
else
cout << (area[area_x][area_y]) ;
}
cout << endl;
}
The problem is with checking if that varaible is set, it is a char area[20][50];
how can I properly check if a variable is empty (not set) in c++ ?
In C++, objects of scalar types are not zero-initialized. They are default-initialized, which means the value they get at initialization is undefined.
In particular, the value is unlikely to be 0 for char
s, int
, etc., and definitely you shouldn't rely on it to have any particular value. If you want your array cells to be initialized to 0 before you start working with them, you have to initialize them manually.
If you come from a Java world, you might think this is an unnecessary bulk of work, but consider that you're working with C-style arrays, and C is not meant to sacrifice performance for programmer time. There are cases where an initialization to 0 would uselessly waste CPU time, and you don't want to pay for what you don't use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With