How does Stockfish know if the king is in check? I am writing a chess engine. I need to know how to tell if the king is in check. I was thinking that maybe I can use the approach that Stockfish uses. Where and how in Stockfish's code is check detected?
If you're curious about the Stockfish code, it can be found here:
 si-&gt;checkersBB = attackers_to(square&lt;KING&gt;(sideToMove)) &amp; pieces(~sideToMove);


We call the attackers_to method to figure out if any pieces are attacking the king's position, including pieces on the king's side.

 Bitboard Position::attackers_to(Square s, Bitboard occupied) const {

    return  (pawn_attacks_bb(BLACK, s)       &amp; pieces(WHITE, PAWN))
         | (pawn_attacks_bb(WHITE, s)       &amp; pieces(BLACK, PAWN))
         | (attacks_bb&lt;KNIGHT&gt;(s)           &amp; pieces(KNIGHT))
         | (attacks_bb&lt;  ROOK&gt;(s, occupied) &amp; pieces(  ROOK, QUEEN))
         | (attacks_bb&lt;BISHOP&gt;(s, occupied) &amp; pieces(BISHOP, QUEEN))
         | (attacks_bb&lt;KING&gt;(s)             &amp; pieces(KING));
 }


We then call the pieces function, which returns all the pieces owned by the opposite side

Finally, we run an AND operator to confirm if any of the opposite side's pieces are threatening the king.


The code is very well written and relatively straightforward to follow, in case you'd like to explore it further.