Fix “invalid operands to binary” in C
Every binary operator in C restricts its left and right operand categories. Applying integer-only `%` or `<<` to `double`, adding two pointers `low + high` during binary search, or comparing two structs directly with `==` triggers `invalid operands to binary`.
Quick Fix Summary
Use fmod(x, y) from <math.h> for floating-point remainder, write low + (high - low) / 2 when computing midpoint pointers, compare struct fields explicitly, and parenthesize (*total) += x when updating through a pointer.
Why This Error Happens
Why low + high fails on pointers in binary search
Subtracting two pointers into the same array (high - low) yields a ptrdiff_t distance, and adding an integer offset (low + (high - low) / 2) yields a valid midpoint pointer—whereas low + high has no meaning in flat address space.
Operator precedence trap: *sum + 1 vs (*sum)++
Writing sum + 1 when sum is int * performs pointer arithmetic rather than integer addition; dereference *sum + 1 to add to the pointed-to integer.
Top Root Causes & Specific Code Fixes
Using % on float or double operands
The built-in `%` operator is defined solely for integer types in C.
double angle = 370.5 % 360;#include <math.h>
double angle = fmod(370.5, 360.0);Adding two pointers (low + high) / 2
Pointer + pointer is illegal; compute `low + (high - low) / 2` instead.
int *mid = (low + high) / 2;int *mid = low + (high - low) / 2;Complete Broken and Corrected Programs
Compare the source before running it. The broken program is intentionally incorrect; its behavior can depend on the compiler and platform.
Read the broken program
#include <stdio.h>
int main(void) {
double total = 10.5;
double rem = total % 3;
printf("%.1f\n", rem);
return 0;
}Open broken program in compilerRead the corrected program
#include <stdio.h>
#include <math.h>
int main(void) {
double total = 10.5;
double rem = fmod(total, 3.0);
printf("%.1f\n", rem);
return 0;
}Open corrected program in compilerExpected output from the corrected program
Reference output, not a live execution result.
1.5Debugging Techniques and Commands
gcc -std=c17 -Wall -Wextra main.c -o app
GCC prints the exact left and right operand types inside `(have ... and ...)`.
(*ptr) += delta;
Parenthesizing dereferences eliminates precedence surprises with binary operators.
Frequently Asked Questions
Can I compare two C structs using a == b?
No. ISO C does not generate member-by-member `==` for structs (padding bytes may contain indeterminate values); write a comparison helper that checks each field.
Why does "hello" + "world" report invalid operands to binary +?
String literals decay to `char *` pointers in expressions, and C forbids adding two pointers. Adjacent literals `"hello " "world"` concatenate at compile time, or use `snprintf` at runtime.
How does fmod handle negative numbers?
`fmod(x, y)` returns a remainder with the same sign as `x`.