C-language generic programming

Source: Internet
Author: User
1 Problem Introduction

First, introduce a problem to implement a generic swap function, using C + + and C implementations, respectively.

2 generics for C + +

C + + has a good generic programming mechanism, so I quickly wrote the C + + version of the generic swap function.

Template<typename t>void Myswap (t &a, t &b) {T c = a;a = B;b = C;}
3 C-Language generics

My first idea is that since you can't exchange variables directly (type doesn't know), then swap pointers. Next moment, I would like to slap myself! Is it an lvalue, and you exchange pointers? stupid!

Then pass in one more parameter, pass in the size, then we can exchange the memory directly according to the size. Good idea:

void Myswapc (void* A, void *b, int size) {void *p = (void*) malloc (size); assert (P! = NULL); memcpy (P, a, size); memcpy (A, B, s ize); memcpy (b, p, size);}
4 Summary

Using certain skills, C language can also achieve a certain function of generic programming, but when programming must be more careful, C language generic programming is not perfect, and there is not enough type check, so it is easy to error.

C-language generic programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.