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.

sizeof PHP vs C

Last updated at Posted at 2019-06-01

株式会社オズビジョンのユッコ (@terra_yucco) です。
今日はびっくりしたことを 1 つだけ。

TL;DR

sizeofcount のエイリアス

※いや、今日はこの後もそんなに長くない

PHP の sizeof は配列の要素数

基本的に入社時に見たコードがそれだったのか、自分はずっと count() を使っていました。
しかし、ある人のコードで sizeof() を見かけ、アレ?となった次第。

この関数は次の関数のエイリアスです。 count().

潔すぎて変な声でました。

C 言語の sizeof は占有メモリの byte 数

前職は C 言語だったのですが、この仕様で結構バグだしたなあと遠い目を。

[2019-06-02] 早速バグだしてました。paiza.IO で実行確認したものに貼り替えておきます。
[2019-06-03] 再度ご指摘を頂いたので Wandbox にて実行確認。

# include <stdio.h>

int main(void) {
    
    char c = 'a';
    printf("%zu\n", sizeof(c)); /* => 1 */

    char str[4];
    str[0] = 'a';
    str[1] = 'b';
    str[2] = 0x00;
    printf("%zu\n", sizeof(str)); /* => 4 */

    char str2[] = "Hello!";
    printf("%zu\n", sizeof(str2)); /* => 7 */
    printf("%zu\n", sizeof(*str2)); /* => 1 */

    int num = 5;
    printf("%zu\n", sizeof(num)); /* => 4 (系依存) */
}

Conclusion

C と PHP は同名同機能の関数も多いのですが、こういうように偶に違いがあってそこで迷います。
違いを理解した上で、それぞれの言語でベストなやり方を見つけていきたいなと感じました。

※久々に C を書いたら文字列を ' でくくってしまって怒られた…。

0
0
5

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?