0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C言語 インクリメント演算子を使用した簡略記法

Last updated at Posted at 2020-03-03

プログラミングができる人に教えてもらうと、読めない書き方で返ってくることがある。簡略記法だ。
これをマスターすれば、他の人が書いたプログラムが読めるようになるので早めに身に着けて置きたい。

インクリメント演算子(後置・前置)

デクリメント演算子も同様です。

# include <stdio.h>
 
int main(void)
{
    /* 後置・前置インクリメント単体 */
    int a =1;
    int b =1;

    a++;
    ++b;

    printf("a=%d, b=%d\n\n", a,b);

    /* 後置インクリメント */
    int x = 2;
    int y;
 
    // xの値をyに格納し、xの値をインクリメントする
    y = x++;
    printf("後置 x++\nx=%d, y=%d\n\n", x,y);


    /* 前置インクリメント */
    x = 2;
    y = 0;

    // xの値をインクリメントし、yにxの値を格納
    y = ++x;
    printf("前置 ++x\nx=%d, y=%d\n", x,y);

    return 0;
}

結果

a=2, b=2

後置 x++
x=3, y=2

前置 ++x
x=3, y=3

おまけ


# include <stdio.h>
 
int main(void)
{
    char a[] = "aiueo";

    int i = 0;
    while (a[++i]) printf("%c\n",a[i]);
    printf("%d\n", i);

    printf("==========\n");

    i = -1;
    while (a[++i]) printf("%c\n",a[i]);
    printf("%d\n", i);

    printf("==========\n");

    i = -1;
    while (a[i++]) printf("%c\n",a[i]);
    printf("%d\n", i);

    printf("==========\n");

    return 0;
}

結果

i
u
e
o
5
==========
a
i
u
e
o
5
==========
a
i
u
e
o

6
==========

参考

C言語入門 - (前置・後置)インクリメント演算子, ++ - Webkaru
https://webkaru.net/clang/increment/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?