2006-11-25から1日間の記事一覧

代入演算子とコピー・コンストラクタを明示的に定義する

#include <iostream.h> #include <string.h> class CBook { char* ptitle; int price; public: CBook(const CBook&); CBook(const char* , int); ~CBook(){delete[] ptitle;} const char* get_title(){return ptitle;} CBook& operator=(const CBook&); }; CBook& CBook::operator=</string.h></iostream.h>…

デフォルトの代入演算子を使用時の問題

#include <iostream.h> #include <string.h> class CBook { char* ptitle; int price; public: CBook(const char* , int); ~CBook(){delete[] ptitle;} const char* get_title(){return ptitle;} }; CBook::CBook(const char* ptitle_, int price_) : price(price_) { ptitle = new</string.h></iostream.h>…

データ・メンバーを宣言する順序に問題がある

#include <iostream> #include <string> using namespace std; class CEmployee { int salary; int age; string name; public: CEmployee(const string&, int); int get_salary(){return salary;} const string get_name(){return name;} }; CEmployee::CEmployee(const string</string></iostream>…

コンストラクタとデストラクタが呼び出されるタイミングを調べるプログラム

#include <iostream> using namespace std; class CFoo { int num; public: CFoo(int n):num(n) {cout << "コンストラクタが呼ばれました:" << num << '\n';} ~CFoo() {cout << "デストラクタが呼ばれました :" << num << '\n';} }; int main() { CFoo foo1(1); CFoo</iostream>…

takagi.in - 高木信尚ホームページ

http://takagi.in/index.php

Microsoft API and Reference Catalog

MSDNのドキュメント「MBCSのプログラミングについて」

文字列の連結

#include <stdio.h> #include <string.h> int main(void) { char s1[] = "Nikkei "; char s2[] = "Software"; char t[20]; strcpy(t, s1); strcat(t, s2); printf("tの内容:%s\n", t); return 0; }sprintf関数を使うこともできる。 #include <stdio.h> int main(void) { char s1[] = "Nik</stdio.h></string.h></stdio.h>…

ポインタを使って文字列をコピーする

#include <stdio.h> void string_copy(char *pdest, char *psrc) { while(*psrc != '\0') *pdest++ = *psrc++; *pdest = '\0'; } int main(void) { char src[] = "Nikkei Software"; char dest[20]; string_copy(dest, src); printf("src = %s\n", src); printf("dest</stdio.h>…

int型のデータをchar*型,short*型,int*型,float型のポインタでアクセス

#include <stdio.h> int main(void) { int n = 0x12345678; char *pc = &n; short *ps = &n; int *pi = &n; float *pf = &n; printf("*pc = %x\n", *pc); printf("*ps = %x\n", *ps); printf("*pi = %x\n", *pi); printf("*pf = %x\n", *pf); return 0; }実行結果 *pc</stdio.h>…

整数型変数の型を決める際の原則

c

ビットフラグなど、ビット単位の情報が重要なものは符号なし整数にする 配列の要素数が多いなど、サイズが重要な場合にはできるだけ小さいデータ型にする さもなければint

intとunsigned intの値を比較する場合。

intがunsigned intに変換されてから比較が行われるため、予期しない結果になることがある。

char型はint型に格上げされてから演算が実行される

#include <stdio.h> int main(void) { char a, b, c, d; a = b = c = d = 100; printf("a + b + c + d = %d\n", a + b + c + d); return 0; }実行結果 a + b + c + d = 400</stdio.h>

整数同士で割り算すると結果は整数になる

オペランド自身をdouble型にキャストする必要がある。

C言語が用意する基本データ型

c

型 サイズ(バイト) 表現できる値の範囲 signed char 1 -128〜127 short int 2 -32768〜32767 int 4 -2147483648〜2147483647 long int 4 -2147483648〜2147483647 unsigned char 1 0〜255 unsigned short int 2 0〜65535 unsigned int 4 0〜4294967295 uns…