Checking for the presence of char

I have a little 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 checking if this varaible is installed, it is char area[20][50];

how can I correctly check if a variable is empty (not set) in C ++?

+3


source to share


2 answers


In C ++, objects of scalar types are not zero-initialized. They are initialized by default, which means that the value they receive upon 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 must initialize them manually.



If you come from the Java world, you might think that this is an extra piece of work, but consider that you are working with C-style arrays, and C does not mean sacrificing performance for the programmer's time. There are times when initializing to 0 wastes CPU time and you don't want to pay for what you don't use.

+5


source


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

Your code in java works because in Java all primitive data types that are created but not initialized are assigned to the compiler by default. In the case of char, this is '\ u0000', which is equivalent to 0.



In C ++, the values ​​of these symbols are undefined. If you want the same behavior, you will need to explicitly set all characters to 0 before you check.

+3


source







All Articles