Lesson 4 of 23

wc -c

wc -c: Count Characters

wc (word count) counts lines, words, and characters in a file. With -c it counts bytes (characters):

$ echo "Hello" | wc -c
6

Six because "Hello" is 5 characters plus the newline echo appends.

Your Implementation

Write int count_chars(const char *s) that returns the total number of characters in the string, including newlines.

int count_chars(const char *s) {
    int n = 0;
    while (*s++) n++;
    return n;
}

This is essentially strlen — walk the string until the null terminator, counting each step.

The Null Terminator

C strings end with a '\0' byte. The pointer arithmetic while (*s++) works because:

  1. *s dereferences the pointer to get the current character
  2. s++ advances the pointer (but evaluates before incrementing, so we read the character first)
  3. When *s is '\0' (zero / false), the loop ends

Your Task

Implement count_chars that returns the number of characters in the string.

TCC compiler loading...
Loading...
Click "Run" to execute your code.