Home > OS >  Adding bool values
Adding bool values

Time:03-05

bool comapare(int val)
{
  if(val>5)
   {
     return true;
   }
 return false;
}

int myFunct(int x,int y)
{
  int count = 0;
  count = (int)compare(x)   (int)compare(y);
  return count;
}

I want to add bool values as above. Is typecasting it as such the best approach to do so. Any comments.

CodePudding user response:

There is no need to cast the values. You could just write

 count = compare(x)   compare(y);

The operands will be promoted to the type int due to the integer promotions and the result also will have the type int.

And as the count can not have a negative value it is better to declare it as having an unsigned integer type as for example size_t or at least unsigned int.

Also the function compare can be written simpler

bool comapare(int val)
{
    return val > 5;
}

In C the type bool is a typedef name for the integer type _Bool.

CodePudding user response:

I see why you are doing it but its confusing to read. BTW the cast is not needed

int myFunct(int x,int y)
{
  int count = 0;
  count = compare(x)   compare(y);
  return count;
}

works fine, but I would do

int myFunct(int x,int y)
{
   int count = 0;
   if (compare(x)) count  ;
   if (compare(y)) count  ;

    return count;
 }

The intent is much clearer.

  • Related