Thread: concept problem

  1. #1
    F#ck me Freddy!!
    Join Date
    Sep 2013
    Location
    jaipur
    Posts
    79

    concept problem

    hi,
    i saw this code somewhere but did not get the concept behind it.why the output is nothing?
    Code:
    #include<stdio.h>
    
    
    int main(void)
    {
     
    printf(5+"good");
    }

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    "good" is an array of five characters with value 'g', 'o', 'o', 'd', and '\0' (also referred to as terminating zero).

    The expression 5+"good" treats the array "good" as if it is a pointer to char, with the value equal to the address of the letter 'g'. 5+"good" is therefore equal to the address of a char 5 past the letter 'g' (i.e. one past the end of the array).

    printf() therefore receives a pointer to a char which contains the address of a character one past the terminating zero.


    The problem with your example is that it is not guaranteed to produce nothing. There is no guarantee that a char exists which is one past the terminating zero. Your code therefore exhibits undefined behaviour. That means any result your program produces is valid. It might print horses. It might print nothing. It might reformat your hard drive and try to download and install windows 8.1 to it. Any result is acceptable because the code exhibits undefined behaviour.

    If the statement has been printf(2 + "good"), then printf() would have started printing at the second 'o', and kept going until it encountered the terminating zero. So it would have printed "od" (without the quotes). If the statement had been printf(4 + "good") printf() would have immediately encountered the terminating zero and returned, so it would print nothing.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. triangle problem concept help
    By Abhas in forum C Programming
    Replies: 19
    Last Post: 04-14-2011, 12:57 PM
  2. Concept
    By kusal in forum C Programming
    Replies: 12
    Last Post: 01-06-2007, 10:32 PM
  3. Nice concept..
    By vasanth in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 05-18-2004, 02:59 PM
  4. Concept help
    By Mithoric in forum Windows Programming
    Replies: 13
    Last Post: 04-18-2004, 03:05 PM
  5. Dos programming Concept problem.
    By L.O.K. in forum A Brief History of Cprogramming.com
    Replies: 9
    Last Post: 12-17-2002, 03:25 AM