C
Version
Running C on GCC v12.2.0
Supported languages
C
Testing framework
Special reminders and implementation details
#include <criterion/criterion.h>
#include <criterion/redirect.h>
#include <unistd.h>
#include "HelloWorld.h"
TestSuite(HelloWorld);
Test(HelloWorld, should_display_hello_world)
{
cr_redirect_stdout();
print(STDOUT_FILENO, "Hello World");
cr_assert_stdout_eq_str("Hello World");
}Included libraries
Reading input (stdin)
Programs that read values use standard input. Run opens an interactive terminal: the program starts, prints its prompt, and you type the answer and press Enter, as in a real terminal. The tests of an output-test challenge feed the input themselves.
#include <stdio.h>
#include <string.h>
int main(void) {
char name[100];
if (fgets(name, sizeof name, stdin) == NULL) {
return 0;
}
name[strcspn(name, "\n")] = '\0';
printf("Hello, %s!\n", name);
return 0;
}fgets keeps the newline, which strcspn strips; it returns NULL at end-of-file. scanf("%d", &n) works for numbers. Do not print a prompt before reading in output-test challenges: it would become part of the compared output.
How to debug
Debugging C code is crucial for every developer. One of the simplest yet effective ways to debug is by using printf statements.
Steps to Debug Using printf Statements
Identify the Problem Area: Locate the section of your code where you suspect the problem might be.
Insert
printfStatements: Addprintfstatements before and after the suspected problematic code to print out variable values and flow control.Check the Results Output of your tests
Analyze the Output: Look at the values printed on the results console to understand what's going wrong in your code. Adjust your code based on the findings and repeat as necessary.
Here’s an example of how to use printf for debugging:
C Code
#include <stdio.h>
int calculate_sum(int a, int b) {
printf("calculate_sum called with arguments: %d, %d\n", a, b); // Log function call
int sum = a + b;
printf("Sum after addition: %d\n", sum); // Log sum calculation
return sum;
}
int main() {
int result = calculate_sum(5, 10);
printf("Result of calculate_sum: %d\n", result); // Log the result
return 0;
}