Like Tree1Likes
  • 1 Post By rags_to_riches

output of following c code

This is a discussion on output of following c code within the C Programming forums, part of the General Programming Boards category; Code: #include<stdio.h> void main() { int a; printf("a contains %d\n"); } this is giving some junk value where as Code: ...

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    5

    output of following c code

    Code:
    #include<stdio.h>
    void main()
    {
    int a;
    printf("a contains %d\n");
    }
    this is giving some junk value where as
    Code:
    #include<stdio.h>
    void main()
    {
    float a;
    printf("a contains %f\n");
    }
    this is not giving any value.I am not getting why is it so and could you please tell me what is the concept behind it?

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,170
    %d and %f tell printf() than an additional argument has been passed. Your code does not pass an additional argument, so exhibits undefined behaviour.

    Your first example needs to be
    Code:
    #include<stdio.h>
    int main()
    {
    int a;
    printf("a contains %d\n", a);
    }
    Note the changes I have highlighted in red.
    Right 98% of the time, and don't care about the other 3%.

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,422
    a still needs to be initialised though, before trying to print it.
    int a = 42;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,648
    It's int main(void), not void main(). Let me guess...Turbo C?

    And this should be in C Programming, not C++.

    EDIT: Oops. grumpy already covered the int main issue.
    Salem likes this.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. what is the output of this code
    By C_Enthusiast in forum C Programming
    Replies: 2
    Last Post: 01-07-2011, 05:07 AM
  2. what is the output of this code?
    By karthik537 in forum C Programming
    Replies: 15
    Last Post: 09-16-2009, 11:20 AM
  3. Output of code
    By lesodk in forum C++ Programming
    Replies: 5
    Last Post: 05-17-2009, 08:56 AM
  4. What will be the output of the following code?
    By developersubham in forum C++ Programming
    Replies: 13
    Last Post: 01-02-2007, 06:36 AM
  5. same code different output
    By kashifk in forum C Programming
    Replies: 4
    Last Post: 03-18-2003, 01:51 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21