Check a Palindrome
แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Check a Palindrome
Check a Palindrome คืออะไร?
แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Check a Palindrome
แก้โจทย์ Check a Palindrome ด้วย code C และ C++ ที่รันได้
ประเด็นสำคัญ
- เปิด compiler warning และแก้ทุกคำเตือน
- รู้ type และ lifetime ของทุกค่า
- ตรวจ input และขอบเขต array ให้ชัดเจน
ตัวอย่างโค้ด C และ C++
main.c
#include <stdio.h>
#include <string.h>
int main(void) {
const char *text = "level"; size_t length = strlen(text); int palindrome = 1;
// Compare characters mirrored around the center.
for (size_t i = 0; i < length / 2; ++i)
if (text[i] != text[length - 1 - i]) { palindrome = 0; break; }
printf("%s is %sa palindrome\n", text, palindrome ? "" : "not ");
}
level is a palindrome
C++
main.cpp
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string text = "level";
// equal compares the first half with a reversed view.
bool palindrome = std::equal(text.begin(), text.begin() + text.size() / 2, text.rbegin());
std::cout << text << " is " << (palindrome ? "" : "not ") << "a palindrome\n";
}
level is a palindrome
เปรียบเทียบ 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