Chinaunix首页 | 论坛 | 博客
  • 博客访问: 222459
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: C/C++

2011-03-16 14:12:12

2.1 Increment and Decrement Operators

2011-03-16 Wed

C provides two unusual operators for incrementing and decrementing variables. The increment operator ++ adds 1 to its operand, while decrement operator subtracts 1.

The unusual aspect is that ++ and may be used either as prefix operators, or postfix operators. In both cases, the effect is to increment n. But the expression ++n increments n before its value is used, while n++ increments n after its value has been used.

  1. int n = 5;
  2.  x = n++ -> x = 5; n = 6;
  3.  x = ++n -> x = 6; n = 6;

The increment and decrement operators can only be applied to variables; an expression like (i+l)++ is illegal.

In a context where no value is wanted, just the incrementing effect, as in

  1. if (c == '\n')
  2.     nl++;

prefix and postfix are the same. But there are situations where one or the other is specifically called for. For instance, consider the function squeeze(s,c), which removes all occurrences of the character c from the string s.

  1. /* squeeze: delete all c from s */
  2. void squeeze(char s[], int c)
  3. {
  4.         int i, j;

  5.         for (i = j = 0; s[i] !='\0'; i++)
  6.           if (s[i] != c)
  7.                 s[j++] = s[i];
  8.         s[j] = '\0';
  9. }

Each time a non-*c* occurs, it is copied into the current j position, and only then is j incremented to be ready for the next character. This is exactly equivalent to

  1. if (s[i] != c) {
  2.    s[j] = s[i];
  3.    j++;

Date: 2011-03-16 14:07:41 EDT

HTML generated by org-mode 7.4 in emacs 23

阅读(422) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~