Why does this for loop exit on some platforms and not on others?

前端 未结 14 2736
执念已碎
执念已碎 2020-12-12 09:00

I have recently started to learn C and I am taking a class with C as the subject. I\'m currently playing around with loops and I\'m running into some odd behaviour which I d

14条回答
  •  北海茫月
    2020-12-12 09:41

    It is undefined at array[10], and gives undefined behavior as described before. Think about it like this:

    I have 10 items in my grocery cart. They are:

    0: A box of cereal
    1: Bread
    2: Milk
    3: Pie
    4: Eggs
    5: Cake
    6: A 2 liter of soda
    7: Salad
    8: Burgers
    9: Ice cream

    cart[10] is undefined, and may give an out of bounds exception in some compilers. But, a lot apparently don't. The apparent 11th item is an item not actually in the cart. The 11th item is pointing to, what I'm going to call, a "poltergeist item." It never existed, but it was there.

    Why some compilers give i an index of array[10] or array[11] or even array[-1] is because of your initialization/declaration statement. Some compilers interpret this as:

    • "Allocate 10 blocks of ints for array[10] and another int block. to make it easier, put them right next to each other."
    • Same as before, but move it a space or two away, so that array[10] doesn't point to i.
    • Do the same as before, but allocate i at array[-1] (because an index of an array can't, or shouldn't, be negative), or allocate it at a completely different spot because the OS can handle it, and it's safer.

    Some compilers want things to go quicker, and some compilers prefer safety. It's all about the context. If I was developing an app for the ancient BREW OS (the OS of a basic phone), for example, it wouldn't care about safety. If I was developing for an iPhone 6, then it could run fast no matter what, so I would need an emphasis on safety. (Seriously, have you read Apple's App Store Guidelines, or read up on the development of Swift and Swift 2.0?)

提交回复
热议问题