How to Code in C/C++ Using AI
Use an AI assistant to write a small C function, compile it, and prove it with tests. C and C++ still power operating systems, embedded devices, games and high-speed services.
In short: say C11 or C++17, “no extra libraries”, give one example with the exact answer, ask for a tiny test file, then run gcc (or g++) yourself.
Why C/C++ with AI
Banks, telecom, cars and game engines still ship a lot of C and C++. AI writes the boilerplate fast, but memory bugs in these languages crash hard. You must compile with warnings on and run tests.
What you need
- A compiler: gcc/clang on Linux or Mac; MinGW or MSVC on Windows. Check with
gcc --version. - Make (optional): a Makefile to build and test with one command.
- IDE + assistant: VS Code with C/C++ extension + Copilot or Claude Code; or CLion with Copilot.
- Sanitizers (later): AddressSanitizer catches many memory bugs: compile with
-fsanitize=address.
How it flows
Install and check
- Linux:
sudo apt install build-essential(Debian/Ubuntu) or the equivalent for your distro. - Mac: install Xcode Command Line Tools (
xcode-select --install). - Windows: install MinGW-w64 or use Visual Studio Build Tools.
- Check:
gcc --version. For C++ also checkg++ --version.
Step 1 — the prompt
Write a C11 function int is_valid_pin(const char *pin) that checks an Indian PIN code shape: exactly 6 digits after trimming spaces, first digit 1–9 (not 0). Return 1 if valid, 0 otherwise. No extra libraries. Example: "411001" → 1, "000001" → 0. Only return the .c file with the function.
Step 2 — the code (tested here)
pin.c/* pin.c — Indian PIN code shape check (6 digits, first 1–9). */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int is_valid_pin(const char *pin) {
if (pin == NULL) return 0;
/* skip leading spaces */
while (*pin && isspace((unsigned char)*pin)) pin++;
size_t n = 0;
while (pin[n] && !isspace((unsigned char)pin[n])) n++;
if (n != 6) return 0;
if (pin[0] < '1' || pin[0] > '9') return 0;
for (size_t i = 1; i < 6; i++) {
if (pin[i] < '0' || pin[i] > '9') return 0;
}
return 1;
}
#ifdef PIN_MAIN
int main(void) {
printf("%d\n", is_valid_pin("411001")); /* Pune sample */
return 0;
}
#endifgcc -Wall -Wextra -std=c11 -DPIN_MAIN -o pin pin.c
./pin
# -> 1Step 3 — ask for tests, then run them
Write a separate test_pin.c that uses assert() for: valid Pune and Delhi PINs, leading zero, too short, a letter, trimmed spaces, and NULL. Print how many checks passed.
/* test_pin.c — tiny assert tests for is_valid_pin */
#include <stdio.h>
#include <assert.h>
int is_valid_pin(const char *pin);
int main(void) {
assert(is_valid_pin("411001") == 1); /* Pune */
assert(is_valid_pin("110001") == 1); /* Delhi */
assert(is_valid_pin("000001") == 0); /* first digit 0 */
assert(is_valid_pin("41100") == 0); /* too short */
assert(is_valid_pin("411001a") == 0); /* letter */
assert(is_valid_pin(" 411001 ") == 1); /* trim spaces */
assert(is_valid_pin(NULL) == 0);
printf("7 checks passed\n");
return 0;
}gcc -Wall -Wextra -std=c11 -o test_pin pin.c test_pin.c
./test_pin
# -> 7 checks passedC++ tip
- For C++, say “C++17, use
std::string_view, no rawnew” in the prompt. - Compile with
g++ -Wall -Wextra -std=c++17. - Prefer
std::optional/ exceptions for errors in library code; avoid silent failures.
Settings and config
- Rules file: “C11/C++17, -Wall -Wextra, no gets(), check every malloc, add a small test file”.
- VS Code: install the Microsoft C/C++ extension so IntelliSense and compile errors show in the editor.
- Turn warnings into errors in CI:
-Werror.
Watch out (common AI mistakes in C/C++)
- Buffer overflows — always pass a max length; prefer
snprintfoversprintf. - Forgetting to free — or double-free; ask for clear ownership rules.
- Wrong size with
sizeofon pointers vs arrays. - Mixing C and C++ headers — say which language in the prompt.
- Ignoring compiler warnings — fix every warning before you trust the code.
Try this yourself: ask AI for a paint-can helper in C or C++, then prove the cases
Hello friends. The live chapter already walked through is_valid_pin in C. This practice is a different fictional studio called Amber Wick Atelier. You ask an AI for cans_needed, which returns how many whole paint cans cover an area given coverage per can, using ceiling math and clear validation. On this drafting machine /usr/bin/g++ is only a symlink to gcc and cannot compile C++, so we verified a C twin with gcc 14.2.0: the starter failed 6 cases and passed 2, and the fixed build printed 8 passed. Keep the C++ header for machines that have a real g++.
नमस्कार मित्रांनो. Live chapter मध्ये is_valid_pin हा C उदाहरण आधीच आले आहे. हा सराव Amber Wick Atelier नावाच्या वेगळ्या काल्पनिक स्टुडिओवर आहे. तुम्ही AI कडून cans_needed मागता जे area आणि प्रत्येक डब्याच्या coverage वरून किती पूर्ण paint cans लागतील हे ceiling गणिताने आणि स्पष्ट validation ने काढते. या drafting मशीनवर /usr/bin/g++ फक्त gcc चा symlink आहे आणि C++ compile करू शकत नाही, म्हणून आम्ही C twin gcc 14.2.0 ने सिद्ध केला: starter मध्ये 6 fail आणि 2 pass, आणि fixed build ने 8 passed छापले. खरा g++ असलेल्या मशीनसाठी C++ header जपून ठेवा.
नमस्ते दोस्तों. Live chapter में is_valid_pin वाला C उदाहरण पहले आ चुका है. यह अभ्यास Amber Wick Atelier नाम के अलग काल्पनिक स्टूडियो पर है. आप AI से cans_needed मांगते हो जो area और प्रति डिब्बे coverage से पूरे paint cans की संख्या ceiling गणित और साफ़ validation से निकाले. इस drafting मशीन पर /usr/bin/g++ सिर्फ gcc का symlink है और C++ compile नहीं कर सकता, इसलिए हमने C twin को gcc 14.2.0 से साबित किया: starter में 6 fail और 2 pass, और fixed build ने 8 passed छापा. असली g++ वाली मशीन के लिए C++ header बचाए रखो।
Ravindra Bagale's Tip
Ask for ceiling with std::ceil in C++ or ceil in C, and name the exception or error substrings the tests search for. Compile the starter first so you see truncating divide fail on 10.0 / 3.0, then ask the AI to fix only the failing cases.
Ravindra Bagale's Tip – मराठी
C++ मध्ये std::ceil किंवा C मध्ये ceil मागा, आणि tests शोधत असलेल्या exception किंवा error substrings नावाने सांगा. आधी starter compile करा जेणेकरून 10.0 / 3.0 वर truncating divide fail होताना दिसेल, नंतर AI ला फक्त fail होणारे cases सुधारायला सांगा.
Ravindra Bagale's Tip – हिंदी
C++ में std::ceil या C में ceil मांगो, और tests जिन exception या error substrings को खोजते हैं उन्हें नाम से बताओ. पहले starter compile करो ताकि 10.0 / 3.0 पर truncating divide fail दिखे, फिर AI से सिर्फ वही failing cases ठीक करवाओ।
gcc 14.2.0 to compile and run the C twin. Starter printed 6 failed, 2 passed. Fixed printed 8 passed. /usr/bin/g++ exists but points at gcc and has no cc1plus, so C++ was not compiled on this box and no g++ package was installed. A Python twin under pytest 9.1.1 also passed 8 cases for the fixed logic. Student-facing paint_cans.hpp remains for machines with a real g++.Your task: start from the buggy helper that truncates area / coverage and skips validation. Ask an AI to use ceiling, reject non-finite and non-positive inputs, and keep at least eight cases. Prefer the C files when you are on this kind of gcc-only box; use the C++ header when your machine has a working g++.
Setup
- Create a project folder and open a terminal inside it.
- Confirm a compiler: run
gcc --versionorg++ --version. - Save the header or
.hfile together with the source and the tiny test runner. - Link math when needed: add
-lmfor the C build that callsceil.
Starter C header paint_cans.h:
/* Amber Wick Atelier — shared C header for cans_needed (fictional teaching studio). */
#ifndef PAINT_CANS_H
#define PAINT_CANS_H
/* Returns cans needed, or -1 on invalid input (see cans_needed_last_error). */
int cans_needed(double area_sq_m, double coverage_per_can_sq_m);
const char *cans_needed_last_error(void);
#endif
Starter paint_cans.c (truncates, skips validation):
/* Amber Wick Atelier paint-can helper (fictional teaching studio — not a real shop).
* Starter: truncating divide, no validation.
*/
#include "paint_cans.h"
static char last_err[128];
const char *cans_needed_last_error(void) {
return last_err;
}
int cans_needed(double area_sq_m, double coverage_per_can_sq_m) {
last_err[0] = '\0';
/* Starter bugs: no validation; truncates instead of ceiling. */
return (int)(area_sq_m / coverage_per_can_sq_m);
}
Tiny C test runner test_paint_cans.c:
#include "paint_cans.h"
#include <math.h>
#include <stdio.h>
#include <string.h>
static int failures = 0;
static void expect_eq(const char *name, int got, int want) {
if (got != want) {
fprintf(stderr, "FAIL %s: got %d want %d\n", name, got, want);
failures++;
} else {
printf("PASS %s\n", name);
}
}
static void expect_err(const char *name, double area, double cov, const char *part) {
int got = cans_needed(area, cov);
const char *msg = cans_needed_last_error();
if (got != -1) {
fprintf(stderr, "FAIL %s: expected error containing \"%s\", got %d\n", name, part, got);
failures++;
return;
}
if (msg == NULL || strstr(msg, part) == NULL) {
fprintf(stderr, "FAIL %s: message \"%s\" missing \"%s\"\n", name, msg ? msg : "(null)", part);
failures++;
return;
}
printf("PASS %s\n", name);
}
int main(void) {
expect_eq("exact_ten_over_five", cans_needed(10.0, 5.0), 2);
expect_eq("needs_ceil_ten_over_three", cans_needed(10.0, 3.0), 4);
expect_eq("small_area_one_can", cans_needed(0.5, 5.0), 1);
expect_eq("exact_one", cans_needed(5.0, 5.0), 1);
expect_eq("large_hall", cans_needed(100.0, 12.0), 9);
expect_err("rejects_zero_area", 0.0, 5.0, "positive");
expect_err("rejects_negative_coverage", 10.0, -1.0, "positive");
expect_err("rejects_nan_area", NAN, 5.0, "finite");
if (failures) {
fprintf(stderr, "%d failed\n", failures);
return 1;
}
printf("8 passed\n");
return 0;
}
Optional C++ header for a real g++ paint_cans.hpp (starter shown; throws std::invalid_argument):
// Amber Wick Atelier paint-can helper (fictional teaching studio — not a real shop).
// Starter: rough divide without ceiling or validation.
#pragma once
#include <cmath>
#include <stdexcept>
#include <string>
// Return how many whole cans are needed to cover area_sq_m given coverage_per_can_sq_m.
// Fixed rules: both inputs must be finite and > 0; result is ceil(area / coverage).
inline int cans_needed(double area_sq_m, double coverage_per_can_sq_m) {
// Starter bugs: no validation; truncates instead of ceiling; wrong for exact multiples.
return static_cast<int>(area_sq_m / coverage_per_can_sq_m);
}
Suggested AI ask (copy and adapt):
cpp-prompt.txtWrite a C++17 inline function cans_needed(double area_sq_m, double coverage_per_can_sq_m) in paint_cans.hpp for fictional Amber Wick Atelier. Reject non-finite inputs with std::invalid_argument mentioning finite. Reject area <= 0 or coverage <= 0 with std::invalid_argument mentioning positive. Return ceil(area/coverage) as int, at least 1. Also provide a C11 twin paint_cans.c that returns -1 on error and stores the message in cans_needed_last_error. Add a tiny assert-style runner with at least eight cases including 10/3 needing 4 cans and NaN rejection.
HOW to finish
- Save the starter C files in one folder.
- Ask your AI assistant to add ceiling math and validation.
- Compile with gcc:
gcc -std=c11 -O0 -Wall -Wextra -o test_paint_cans paint_cans.c test_paint_cans.c -lmthen./test_paint_cans. - Expect the buggy starter to show about 6 failed and 2 passed, and the fixed build to print 8 passed.
- Optional on a real g++: compile
test_paint_cans.cppwith the fixedpaint_cans.hppusingg++ -std=c++17.
Real gcc output after the fixed C twin:
gcc-after.txtPASS exact_ten_over_five
PASS needs_ceil_ten_over_three
PASS small_area_one_can
PASS exact_one
PASS large_hall
PASS rejects_zero_area
PASS rejects_negative_coverage
PASS rejects_nan_area
8 passed
Optional completed sources (try it yourself first)
Your AI assistant may reorder the checks. Any version is fine if the eight cases pass.
paint_cans.c/* Amber Wick Atelier paint-can helper (fictional teaching studio — not a real shop). */
#include "paint_cans.h"
#include <math.h>
#include <stdio.h>
static char last_err[128];
const char *cans_needed_last_error(void) {
return last_err;
}
int cans_needed(double area_sq_m, double coverage_per_can_sq_m) {
last_err[0] = '\0';
if (!isfinite(area_sq_m) || !isfinite(coverage_per_can_sq_m)) {
snprintf(last_err, sizeof last_err, "area and coverage must be finite numbers");
return -1;
}
if (area_sq_m <= 0.0) {
snprintf(last_err, sizeof last_err, "area must be positive");
return -1;
}
if (coverage_per_can_sq_m <= 0.0) {
snprintf(last_err, sizeof last_err, "coverage must be positive");
return -1;
}
{
double raw = area_sq_m / coverage_per_can_sq_m;
int cans = (int)ceil(raw);
if (cans < 1) {
cans = 1;
}
return cans;
}
}
Matching C++ header for machines with a real g++:
paint_cans.hpp// Amber Wick Atelier paint-can helper (fictional teaching studio — not a real shop).
#pragma once
#include <cmath>
#include <stdexcept>
#include <string>
// Return how many whole cans are needed to cover area_sq_m given coverage_per_can_sq_m.
// Both inputs must be finite and > 0. Result is the smallest integer >= area/coverage.
inline int cans_needed(double area_sq_m, double coverage_per_can_sq_m) {
if (!std::isfinite(area_sq_m) || !std::isfinite(coverage_per_can_sq_m)) {
throw std::invalid_argument("area and coverage must be finite numbers");
}
if (area_sq_m <= 0.0) {
throw std::invalid_argument("area must be positive");
}
if (coverage_per_can_sq_m <= 0.0) {
throw std::invalid_argument("coverage must be positive");
}
double raw = area_sq_m / coverage_per_can_sq_m;
int cans = static_cast<int>(std::ceil(raw));
if (cans < 1) {
cans = 1;
}
return cans;
}
Troubleshooting
- Problem:
10.0 / 3.0returns 3. Fix: use ceiling so any fraction of a can rounds up to a whole can, which makes the answer 4. - Problem: a tiny area such as 0.5 with coverage 5.0 returns 0. Fix: after ceiling, force a minimum of one can when the inputs are valid and positive.
- Error:
g++: cannot execute cc1plus. Fix: install a real g++ package on your machine, or use the C twin with gcc as this drafting box did. We did not apt-install g++ here because the disk was nearly full. - Problem: NaN still returns a huge integer. Fix: reject non-finite inputs before the divide, with a message that contains
finite.
Practice cards: English and spoken Marathi
Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.
Ask for ceiling, not truncate
Keep a C path when g++ is missing
Truncate नको, ceiling मागा
g++ नसताना C path ठेवा
Quick quiz
1. What does is_valid_pin("411001") return in our example?
1 (valid Pune-shaped PIN).
2. Why reject a PIN starting with 0?
Indian PIN codes use first digit 1–9.
3. Which gcc flags catch many mistakes early?
-Wall -Wextra (and -Werror in CI).
4. Does our function prove the PIN is a real post office code?
No. It only checks the 6-digit shape.
Save tokens and money
Ask for one function and one test file. Paste only the first compiler error; fixing it often clears the next ones. Prefer local compile over sending the whole project to chat.