Arrays and Strings
String Compare
A character-by-character comparison decides whether two strings contain the same text.
compare loop
The loop advances while characters match and neither string has ended.
equality result
Two strings are equal only when both reach `'\0'` at the same position.
String Compare
string_compare.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int sameText(const char left[], const char right[]) {
int i = 0;
while (left[i] != '\0' && right[i] != '\0') {
if (left[i] != right[i]) {
return 0;
}
i++;
}
return left[i] == right[i];
}
int main(void) {
char first[] = "cat";
char second[] = "car";
char third[] = "cat";
int useSecond = 0;
const char *other = useSecond ? second : third;
int same = sameText(first, other);
printf("same=%d\n", same);
return 0;
}
#include <stdio.h>
int sameText(const char left[], const char right[]) {
int i = 0;
while (left[i] != '\0' && right[i] != '\0') {
if (left[i] != right[i]) {
return 0;
}
i++;
}
return left[i] == right[i];
}
int main(void) {
char first[] = "cat";
char second[] = "car";
char third[] = "cat";
int useSecond = 1;
const char *other = useSecond ? second : third;
int same = sameText(first, other);
printf("same=%d\n", same);
return 0;
}
first ← cat, second ← car, third ← cat, useSecond ← 0, other ← cat
14int main(void) {15 char first→ cat[] = "cat";16 char second→ car[] = "car";17 char third→ cat[] = "cat";18 int useSecond→ 0 = 0; //@useSecond=11920 const char *other→ cat = useSecond0 ? secondcar : thirdcat;21 int same = sameText(firstcat, othercat);i ← 0
3int sameText(const char leftcat[], const char rightcat[]) {4 int i→ 0 = 0;5 while (left[i] != '\0' && right[i] != '\0') {i ← 1
pass 1 of 34int i = 0;5while (left[i]c != '\0' && right[i]c != '\0') {6 if (left[i] != right[i]) {7 return 0;8 }9 i→ 1++;10}All 3 passes — pass 1 is the card above pass left[i]right[i]i1 c c 0 → 1 2 a a 1 → 2 3 t t 2 → 3 return left[i] == right[i];
10 }11 return left[i]