Talk to the program—and to individual bits
Use formatted standard I/O, understand the three standard streams, read command-line arguments, and apply basic bitwise operations.
After this lesson
You should be able to
- Match printf and scanf conversion specifiers to argument types.
- Use masks to test, set, and clear selected bits.
Three standard streams
stdin supplies ordinary input, stdout carries ordinary results, and stderr carries diagnostics. Keeping errors on stderr lets a user redirect normal output to a file without mixing it with error messages.
Format strings are contracts. %d expects an int, %lf in scanf expects a pointer to double, and scanf usually needs the address operator &: scanf("%d", &age). Always check scanf's return value before using the result.
int age;
if (scanf("%d", &age) != 1) {
fprintf(stderr, "Expected an integer\n");
return 1;
}
printf("Age: %d\n", age);Arguments and bit masks
With int main(int argc, char *argv[]), argc is the number of command-line strings and argv stores them. argv[0] is normally the program name. Text must be validated and converted before numeric use.
Bitwise & tests shared 1 bits, | sets bits, ^ toggles differing bits, ~ inverts bits, and shifts move bit patterns. A mask such as 1u << 3 selects bit 3. Test with value & mask, set with value | mask, and clear with value & ~mask.
unsigned int mask = 1u << 3;
if ((value & mask) != 0u) {
printf("bit 3 is set\n");
}Try it yourself
Write expressions that set bit 2 and then clear bit 2 in an unsigned value flags.
Need a hint?
Create the mask with 1u << 2. Clearing requires the inverted mask.
Check the worked solution
Set with flags |= 1u << 2; and clear with flags &= ~(1u << 2);.
flags |= 1u << 2;
flags &= ~(1u << 2);Quick check
Where should a validation error normally be written?
Why this lesson exists
Syllabus mapping
Formatted input/output · stdin stdout stderr · Command-line arguments · Bitwise operations
Maps to course outcomes CO2, CO3.