Question

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++ ?

Was it helpful?

Solution

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 chars, 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.

OTHER TIPS

There is no way to check if a variable has been "set" or not. You can only check if it is equal to a specific value.

Your code in java seems to work because, in Java, all primitive data types that are created but not initialized are given a default value by the compiler. In the case of a char, it's '\u0000', which is equivalent to 0.

In c++ the values of these characters are undefined. If you want to have the same behavior, you'll need to explicitly set all of the characters to 0 before you do your check.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top