แบบฝึกหัด C/C++ สำหรับผู้เริ่มต้น

Reverse a String

แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Reverse a String

Reverse a String คืออะไร?

แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Reverse a String

แก้โจทย์ Reverse a String ด้วย code C และ C++ ที่รันได้

ประเด็นสำคัญ

  • เปิด compiler warning และแก้ทุกคำเตือน
  • รู้ type และ lifetime ของทุกค่า
  • ตรวจ input และขอบเขต array ให้ชัดเจน

ตัวอย่างโค้ด C และ C++

C
รันโค้ด →
main.c
#include <stdio.h>
#include <string.h>
int main(void) {
    char text[] = "CodeUtility"; size_t length = strlen(text);
    // Swap mirrored characters in place.
    for (size_t i = 0; i < length / 2; ++i) {
        char temporary = text[i]; text[i] = text[length - 1 - i]; text[length - 1 - i] = temporary;
    }
    puts(text);
}
ผลลัพธ์ที่คาดหวัง
ytilitUedoC
C++
รันโค้ด →
main.cpp
#include <algorithm>
#include <iostream>
#include <string>
int main() {
    std::string text = "CodeUtility";
    // reverse applies swaps across the selected range.
    std::reverse(text.begin(), text.end());
    std::cout << text << '\n';
}
ผลลัพธ์ที่คาดหวัง
ytilitUedoC

เปรียบเทียบ C และ C++

เปรียบเทียบ implementation ของ C และ C++ จากนั้นเปลี่ยน input และทดสอบ edge case เพิ่มเติม

C

C แสดง API แบบ procedural และรายละเอียด representation อย่างชัดเจน

C++

C++ รักษา low-level model และเพิ่ม type ที่ปลอดภัยกว่า

แบบฝึกหัด

รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา

  • เพิ่ม input ผิดและค่าขอบเขต
  • Compile ด้วย -Wall -Wextra -Wpedantic
  • แยก declaration และ implementation