Comaparison of char array element at specific index

{int counter=0;
char arrar[10]={221,254,254,0,0,0,254,222};
for(int l=0; l<10; l++) //This loops on the columns
{cout <<arrar[l];
if(arrar[l]==254)
{
counter=counter+1;
}
}
cout<<counter;}
I should get some value of counter according my logic, but i am getting zero, how can I resolve this and please i want to do it it using char array only.
The max value for a signed char is 127 so your array contains gibberish.
Use unsigned char instead - this should output 3 for your counter
This is a problem with signed/unsigned. See:

1
2
3
4
5
6
7
8
9
10
11
12
// numeric_limits example
#include <iostream>     // std::cout
#include <limits>       // std::numeric_limits

int main () {
  std::cout << std::boolalpha;
  std::cout << "Minimum value for char: " << static_cast<int>(std::numeric_limits<char>::min()) << '\n';
  std::cout << "Maximum value for char: " << static_cast<int>(std::numeric_limits<char>::max()) << '\n';
  std::cout << "char is signed: " << std::numeric_limits<char>::is_signed << '\n';
  std::cout << "Non-sign bits in char: " << std::numeric_limits<char>::digits << '\n';
  return 0;
}
Minimum value for char: -128
Maximum value for char: 127
char is signed: true
Non-sign bits in char: 7



Since the maximum value is limited to 127 a value like 254 is implicitly converted to a negative value.
In order to get the right result you need to explicitly convert the comparison value to char:

if(arrar[l]==static_cast<char>(254))
Topic archived. No new replies allowed.