Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

Friday, February 18, 2011

Problem in swap code

Our only one blog fan, m3rlinez, told me that the one line swap code that I wrote in the previos entry cannot use when two variables are the same allocation such as

a[i] ^= a[j] ^= a[i] ^= a[j]; // when i = j

Thanks him to pointed this issue.

Friday, February 11, 2011

Swap two variable values code in one line.

First code pattern that comes to my mind when I want to swap two variable value is

int c;
c = a;
a = b;
b = c;

I found this code in every novice programming book, also in my programming class.
But I've heard one challenging problem (for me as a novice) that try to swap without temporary variable (that is c, in my code.) The code uses knowledge technique from logic class.

a = a ^ b;
b = a ^ b;
a = a ^ b;

The caret symbol (^) represents bitwise xor.
Recently, I found the code that written it in one line for making it more cool and less understanding that is

a ^= b ^= a ^= b;

Impressed!

Monday, April 12, 2010

[C code] string copy ใน C

ความสุขอย่างนึงในการเขียนโปรแกรมของผมคือการแก้โค้ดที่ทำงานได้ให้มันสั้นลงครับ (แล้วโค้ดที่ทำงานได้มันจะบั๊กก็ตอนแก้ให้สั้นเนี่ยแหละ ฮ่าๆๆ) ไม่รู้สิ รู้สึกว่่ามันเจ๋งดีนะเวลาได้เขียนโค้ด while หรือ for ปล่าวๆแบบให้การทำงานอยู่ในเงื่อนไขของลูปไปเลย เหอๆ
เมื่อวานผมก็อ่านโค้ด string copy ในหนังสือภาษาซีเล่มนึง โค้ดนี้เขียนโดยใช้ใช้พอยท์เตอร์ (เพราะมันอยู่ในบทเรื่องพอยท์เตอร์) โค้ดในหนังสือตอนแรกออกมาเป็นแบบนี้ครับ

void strcpy(char *s, char *t) {
while((*s = *t) != '\0') {
s++;
t++;
}
}

ไอ้คนอย่างผมก็เลยนั่งเขียนให้มันเหลือแค่บรรทัดเดียวไอ้ตรงวน while โค้ดผมได้ออกมาแบบนี้ครับ

void strcpy(char *s, char *t) {
while((*s++ = *t++) != '\0');
}

แฮ่ ในที่สุดมันก็เหลือบรรทัดเดียว ซึ่งพอผมอ่านหนังสือต่อไปมันก็ลดรูปมาเหลือเท่าที่ผมเขียนครับ
แต่ยังไม่หมด ตัวอย่างต่อมามันดันเขียนลูปได้สั้นกว่านี้อีก!!!

void strcpy(char *s, char *t) {
while(*s++ = *t++);
}

โห มันใช้ความบังเอิญที่ว่า character constant '\0' ดันมีค่าเป็น 0 พอดีมาเป็นเงื่อนไขในการเช็ค
สุดยอดไปเลยหวะ ชอบๆ

ก็เลยต้องมาเขียนบล็อกเก็บไว้หน่อย :)

Friday, April 9, 2010

[C code] if in C

ไปอ่านเจอมาจาก stackoverflow (แต่จำกระทู้ไม่ได้เลยไม่ได้ทำลิงค์ไป) เห็นมีคนมาถามว่าเวลาเขียน if เปรียบเทียบตัวแปรกับตัวเลข เขียนแบบนี้มันดีกว่ายังไง

if(4 == i)

งงดิครับ ตั้งแต่เกิดมาไม่เคยเห็นครูบาอาจารย์ที่ไหนบอกว่าเขียนแบบนี้มันดีกว่า ไอ้คนตั้งกระทู้มันก็ไม่รู้ไปได้ยินมาจากไหน แต่ก็มีคนเข้ามาตอบให้ได้ว่าดีกว่ายังไง
โค้ดแบบนี้จะดีกว่าเฉพาะในภาษาซีเท่านั้นครับ เพราะว่าเป็นการลดบั๊กจากการพิมพ์ผิด เพราะว่าในภาษาซีถ้าเราตั้งใจจะเปรียบเทียบค่าโดยพิมพ์แบบนี้

if(i == 4)

เป็น

if(i = 4)

จะได้ว่า if นี้เป็นจริงเสมอ (ส่วนจาวาจะคอมไพล์ไม่ผ่าน) ดังนั้นพอเขียนกลับกัน ถึงเขียนผิดเป็น

if(4 = i)

คอมไพเลอร์ก็จะฟ้องขึ้นมา
แหม่ ไอ้คนคิดวิธีเขียนโค้ดแบบนี้มันสุดยอดจริงๆ