Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 3 · LANGUAGES

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

WHY

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

WHAT
  • 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

1 · Describe the function C11, no libs, example 2 · AI writes .c file read every line 3 · Compile with -Wall fix warnings 4 · Ask for a test file asserts 5 · Run the tests all pass = keep

Install and check

HOW
  1. Linux: sudo apt install build-essential (Debian/Ubuntu) or the equivalent for your distro.
  2. Mac: install Xcode Command Line Tools (xcode-select --install).
  3. Windows: install MinGW-w64 or use Visual Studio Build Tools.
  4. Check: gcc --version. For C++ also check g++ --version.

Step 1 — the prompt

COPY THIS 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;
}
#endif
gcc -Wall -Wextra -std=c11 -DPIN_MAIN -o pin pin.c
./pin
# -> 1

Step 3 — ask for tests, then run them

FOLLOW-UP PROMPT

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
/* 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 passed
Note: this only checks the shape of a PIN. It does not prove the PIN exists in the India Post database.

C++ tip

  1. For C++, say “C++17, use std::string_view, no raw new” in the prompt.
  2. Compile with g++ -Wall -Wextra -std=c++17.
  3. Prefer std::optional / exceptions for errors in library code; avoid silent failures.

Settings and config

  1. Rules file: “C11/C++17, -Wall -Wextra, no gets(), check every malloc, add a small test file”.
  2. VS Code: install the Microsoft C/C++ extension so IntelliSense and compile errors show in the editor.
  3. Turn warnings into errors in CI: -Werror.

Watch out (common AI mistakes in C/C++)

  • Buffer overflows — always pass a max length; prefer snprintf over sprintf.
  • Forgetting to free — or double-free; ask for clear ownership rules.
  • Wrong size with sizeof on 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++.

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.

Practice label: Amber Wick Atelier, every area and every coverage number here is fictional teaching data. It is not a real paint shop. Passing these tests proves only the listed cases.
Environment (tested): on 6 November 2026 this box used preexisting 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

HOW
  1. Create a project folder and open a terminal inside it.
  2. Confirm a compiler: run gcc --version or g++ --version.
  3. Save the header or .h file together with the source and the tiny test runner.
  4. Link math when needed: add -lm for the C build that calls ceil.

Starter C header paint_cans.h:

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):

paint_cans.c
/* 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:

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):

paint_cans.hpp
// 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.txt
Write 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

HOW
  1. Save the starter C files in one folder.
  2. Ask your AI assistant to add ceiling math and validation.
  3. Compile with gcc: gcc -std=c11 -O0 -Wall -Wextra -o test_paint_cans paint_cans.c test_paint_cans.c -lm then ./test_paint_cans.
  4. Expect the buggy starter to show about 6 failed and 2 passed, and the fixed build to print 8 passed.
  5. Optional on a real g++: compile test_paint_cans.cpp with the fixed paint_cans.hpp using g++ -std=c++17.

Real gcc output after the fixed C twin:

gcc-after.txt
PASS 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

HOW
  1. Problem: 10.0 / 3.0 returns 3. Fix: use ceiling so any fraction of a can rounds up to a whole can, which makes the answer 4.
  2. 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.
  3. 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.
  4. 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.

PRACTICE CARDAI Coding

Ask for ceiling, not truncate

Tell the AI that 10 square metres at 3 per can must become 4 cans.
Compile the starter first so the truncating bug is visible.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Keep a C path when g++ is missing

A C twin with gcc can prove the same cases on a gcc-only box.
Still keep paint_cans.hpp for machines that have a working g++.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Truncate नको, ceiling मागा

AI ला सांगा की 10 चौरस मीटर वर प्रति डबा 3 असताना 4 cans लागतात.
आधी starter compile करा जेणेकरून truncating bug दिसेल.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

g++ नसताना C path ठेवा

gcc-only बॉक्सवर C twin समान cases सिद्ध करू शकतो.
तरी खरा g++ असलेल्या मशीनसाठी paint_cans.hpp जपून ठेवा.
Ravindra Bagale · ravindrabagale.com/ai-coding

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

SMART AI USE

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.

Save these cards

INTERVIEW CARDAI Coding

How do you check AI-written C code?

Compile with -Wall -Wextra; fix every warning.
Run a small assert test file; use sanitizers for memory bugs.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

C vs C++ prompts

C: say C11, no libs, explicit sizes.
C++: say C++17, std::string_view, no raw new.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

C with AI in 3

Shape + example in the prompt.
gcc -Wall, then assert tests.
Never ship with warnings ignored.
Ravindra Bagale · ravindrabagale.com/ai-coding