【转】c标准库源代码之strncmp

本文详细解读了一段用于比较两个字符串前N个字符的C++代码片段,通过预处理减少循环次数,显著提高字符串比较效率。文章涵盖字符串操作、字符比较、循环优化等关键知识点,旨在提升读者对C++底层实现的理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/* Compare no more than N characters of S1 and S2,
   returning less than, equal to or greater than zero
   if S1 is lexicographically less than, equal to or
   greater than S2.  */ 
int 
STRNCMP (const char *s1, const char *s2, size_t n) 
  unsigned reg_char c1 = '/0'
  unsigned reg_char c2 = '/0'
   
  if (n >= 4) 
    
      size_t n4 = n >> 2; 
      do 
    
      c1 = (unsigned char) *s1++; 
      c2 = (unsigned char) *s2++; 
      if (c1 == '/0' || c1 != c2) 
        return c1 - c2; 
      c1 = (unsigned char) *s1++; 
      c2 = (unsigned char) *s2++; 
      if (c1 == '/0' || c1 != c2) 
        return c1 - c2; 
      c1 = (unsigned char) *s1++; 
      c2 = (unsigned char) *s2++; 
      if (c1 == '/0' || c1 != c2) 
        return c1 - c2; 
      c1 = (unsigned char) *s1++; 
      c2 = (unsigned char) *s2++; 
      if (c1 == '/0' || c1 != c2) 
        return c1 - c2; 
    } while (--n4 > 0); 
      n &= 3; 
    
   
  while (n > 0) 
    
      c1 = (unsigned char) *s1++; 
      c2 = (unsigned char) *s2++; 
      if (c1 == '/0' || c1 != c2) 
    return c1 - c2; 
      n--; 
    
   
  return c1 - c2; 
}
源代码这么高大上,上学时写的练习题代码爆弱了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值