はじめてのC

K&Rの「プログラミング言語C」を読み始めた!
いろいろ書きながら覚える。

標準入力から一文字ずつ出力
#include <stdio.h>

main()
{   
    int c;
    while ( ( c = getchar() ) != EOF ) {
        if ( c != '\n' )
            printf("%c\n", c);
    }
}
華氏から摂氏変換
#include <stdio.h>

#define LOWER 0
#define UPPER 300
#define STEP  10

float fahr2celsius(float fahr);

main()
{   
    float fahr;
    float celcius;

    for ( fahr=LOWER; fahr <= UPPER; fahr+=20 ) {
        printf("%.1f\n", fahr2celsius(fahr));
    }

    return 0;
}

float fahr2celsius (float fahr)
{  
   return (5.0/9.0) * (fahr - 32.0);
}
文字列
#include <stdio.h>

main()
{
    printf("%s\n", "Hello, World!");
    printf("Hello, World!\n");

    char string[14] = "Hello, World!";
    printf("%s\n", string);

    char string2[6];
    string2[0] = 'H';
    string2[1] = 'e';
    string2[2] = 'l';
    string2[3] = 'l';
    string2[4] = 'o';
    string2[5] = '\0';

    printf("%s\n", string2);
}
gcc -o string string.c ; ./string 
Hello, World!
Hello, World!
Hello, World!
Hello
外部変数
#include <stdio.h>

int  n;
void change_n(void);

main()
{   
    int n = 1;
    printf("n is %d\n", n); // ローカル変数

    change_n();

    printf("n is %d\n", n); // ローカル変数
}

void change_n(void) {
    extern int n; // 同一ソース内で定義されてるので明示的にextern宣言しなくてもOK
    n = 2;        // グローバル変数
    printf("n is %d\n", n);
}
Enum
#include <stdio.h>

int main()
{   
    enum COLOR { RED=1, BLUE, GREEN };

    enum COLOR color;
    color = RED;

    if ( color == RED ) {
        printf("red\n");
    }
}