Thread: why this code Works.

  1. #1
    Registered User
    Join Date
    Feb 2014
    Posts
    2

    why this code Works.

    i asked a newbie to write me a program to print from 1 to 100.
    He gave me this code
    Code:
    #include <stdio.h>
    int main()
    {
    int i,A[100];
    for(i = 1; i <= 100; i++)
    printf("%d\n",A[100]);
    }
    It WORKED..
    Ive ran the code on ubuntu and on windows perfectly.
    I dont understand why it works.
    Can any one help.

  2. #2
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    O_o

    That code does not work; that code only appears to work under specific circumstances.

    Soma
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

  3. #3
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    You're experiencing undefined behavior. The C compiler(s) that you are using places the value of i in the memory location just past the end of your array. There is no guarantee that this will happen all the time, and you should certainly not depend on this behavior.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Was this question really worth cross-posting?

  5. #5
    Registered User Alpo's Avatar
    Join Date
    Apr 2014
    Posts
    877
    How could it even print a different number each time? Shouldn't it just print a single garbage number 99 times?

    Edit: just caught on to what Elkvis said, I got it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How Obfusicated code works
    By acho.arnold in forum C Programming
    Replies: 3
    Last Post: 08-17-2013, 03:27 PM
  2. How come my code works? Seriously. :)
    By assiduus in forum C Programming
    Replies: 15
    Last Post: 02-10-2011, 12:54 PM
  3. Code works, one some files but not others
    By Watts53 in forum C Programming
    Replies: 5
    Last Post: 08-05-2010, 12:21 PM
  4. Replies: 8
    Last Post: 12-21-2008, 09:42 PM
  5. How Do u See if a code works
    By Nos in forum C++ Programming
    Replies: 11
    Last Post: 08-05-2005, 01:34 PM