2

Hello could any one explain to me this line of code written in c++?

couleur[i][c]=couleur[i][c] ||
couleur[noeud][c];

Arrays are char type. What does this or do? ( arrays indexes are meaningless so i don't explain them), because i need to rewrite this line to Java code and in Java i got error "bad operand types for binary ||". I checked this code in c++ and can get what it does - doesn't matter what value chars get it always assign ' '.

Any idea?

Eran Egozi
  • 775
  • 1
  • 7
  • 18
user1291518
  • 89
  • 1
  • 8

2 Answers2

4
a || b

Is for booleans. Both in Java and C++. However, in C++, if a and/or b are not booleans, the compiler will cast them to a boolean first. Anything non-zero becomes true. In Java, this would be:

(a != 0 || b != 0) ? 1 : 0

So, to translate your piece of code, use this:

couleur[i][c] = (couleur[i][c] != 0 || couleur[noeud][c] != 0) ? 1 : 0;

Your ' ' you are getting is probably a null byte (0, or '\0').

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • what about the result in java? You can't assign a boolean to a char – Vincent van der Weele Aug 18 '13 at 15:18
  • 1
    I missed something. Check my update. I guess that your `' '` is in fact 0. (Sometimes represented by `'\0'`) – Martijn Courteaux Aug 18 '13 at 15:21
  • my compiler hinted me to cast result to char – user1291518 Aug 18 '13 at 15:28
  • @user1291518 if `couleur` is used as a string (`char*`) the `\0`'s would mark the end of that string in C while they are legal characters in Java. You might need to take care of that manually. The cast to `char` is required because literal numbers (i.e. `0 : 1`) are considered `int` in Java and that's 32bit while `char` is just 16 > potential loss of precision = you have to cast. – zapl Aug 18 '13 at 15:42
0

In C language you can use OR operator on any value, it will be casted to boolean from compiler with rule that any non-zero value is true. You have to rewrite has:

couleur[i][c]=(couleur[i][c] != 0) || (couleur[noeud][c] != 0);

but you are in trouble because couler[][] is typed as char and Java result is a boolean, so use ternary operator as:

couleur[i][c]=(couleur[i][c] != 0) || (couleur[noeud][c] != 0) ? 1 : 0;
Luca Basso Ricci
  • 17,829
  • 2
  • 47
  • 69