Every search function should have a clear contract: what it takes (array, length, key), what it returns (index, pointer, or boolean), and what happens when the key is absent. Two families exist: sequential (linear) search needs no ordering; interval (binary) search requires sorted data. Decide whether duplicates are allowed and which match is returned.
Remember
int find(const int a[], int n, int key);
/* returns index of a match, or -1 if absent */
Reference
Cheat Sheet
Keep these facts handy while you work with Searching Basics in C in C.
Topic
Detail
Found
Return the index
Absent
Return -1
Duplicates
Define first / last / any
Pointer form
Return NULL if absent
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Linear Search.
Example 1 — Index or -1
Handle both outcomes explicitly.
C
#include <stdio.h>
static int find(const int a[], int n, int key) {
for (int i = 0; i < n; i++)
if (a[i] == key) return i;
return -1;
}
int main(void) {
int a[] = {10, 20, 30, 40, 50};
int keys[] = {40, 35};
for (int i = 0; i < 2; i++) {
int pos = find(a, 5, keys[i]);
if (pos >= 0) printf("%d found at %d\n", keys[i], pos);
else printf("%d not found\n", keys[i]);
}
return 0;
}
Output
40 found at 3
35 not found
How It Works
The caller checks pos >= 0 before treating it as an index.
The same function handles both outcomes.
Document what your function returns for duplicates.
Edge Cases & Pitfalls
Check these before relying on Searching Basics in C in real programs.
unsigned
size_t return values
If your index type is unsigned, -1 becomes a huge value. Use int or a separate flag.
ptr
Returning pointers to local data
Return pointers only into the caller's array.
Remember
Key Takeaways
Define return values.
Handle absent keys.
Choose by data ordering.
One line: Every search function should have a clear contract: what it takes (array, length, key), what it returns (index, pointer, or boolean), and what happens when the key is absent.
Frequently Asked Questions
Commonly the index of the match, or -1 when not found; alternatively a pointer or NULL.
It depends on the function: linear search returns the first by default; binary search may return any match unless you write a first/last variant.
Continue with "C Linear Search" next. Scan the array in order; find first, last, and count matches. The C Searching Algorithms hub lists every topic in order.