Otavio Pliger
Otavio Pliger

Reputation: 11

How this if statement works in C. I know what it does but I can't brake it in pieces

I'm struggling to understand how this if statement works:

if (keyval == GDK_PLUS &&
    (event->state & ~consumed & ALL_ACCELS_MASK) == GDK_CONTROL_MASK)

founded here https://developer.gnome.org/gdk3/stable/gdk3-Keyboard-Handling.html#gdk-keymap-translate-keyboard-state

Full example code:

#define ALL_ACCELS_MASK (GDK_CONTROL_MASK | GDK_SHIFT_MASK | GDK_MOD1_MASK)

gdk_keymap_translate_keyboard_state (keymap, event->hardware_keycode,
                                     event->state, event->group,
                                     &keyval, NULL, NULL, &consumed);

if (keyval == GDK_PLUS &&
    (event->state & ~consumed & ALL_ACCELS_MASK) == GDK_CONTROL_MASK)
    // Control was pressed

My objective is to understand it so I can port it to Vala since the example given in Valadocs is the same written here in C, and not in Vala.

Upvotes: 0

Views: 131

Answers (1)

SIGSTACKFAULT
SIGSTACKFAULT

Reputation: 1035

First part

keyval == GDK_PLUS

This does exactly what it appears -- checks if keyval is equal to GDK_PLUS.


Second part

Let's work outwards.

~consumed

This is a bitwise not. It inverts the bits individually.

00101100 → Bitwise not → 11010011

(event->state & ~consumed & ALL_ACCELS_MASK)

& is bitwise and. It compares the bits in the two operands and sets the bits in the output only if they are both 1. For example,

  binary    hex   dec
  11010111  0xD7  215
& 01101101  0x6D  109
=====================
  01000101  0x45  69

Putting the full second part together:

(event->state & ~consumed & ALL_ACCELS_MASK) == GDK_CONTROL_MASK

This checks if the bitwise and of event->state, ~consumed, and ALL_ACCELS_MASK is equal to GDK_CONTROL_MASK.


Add a comment if you want clarification.

Upvotes: 6

Related Questions