Thread: Code Fragment

  1. #1
    Registered User
    Join Date
    Sep 2013
    Posts
    4

    Code Fragment

    I was given this set of code in my Intro to C class, I have never programmed in C so I am still learning. I though the answer was 7, can someone please explain why the answer is 5 and what can be changed to allow foo to update a without using global variables?

    Code:
    int foo(int a){
    
    a = 7;
    
    
    }
    
    
    int main(){
    
    int a = 5;
    foo(a);
    printf("value is %d\n", a);
    
    }

  2. #2
    Registered User
    Join Date
    Sep 2013
    Posts
    4
    Is it because int foo(int a) should be void foo(int a) ?

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,794
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

  4. #4
    Registered User
    Join Date
    Sep 2013
    Posts
    1

    Post This is my code for your problem

    1 int foo(int number){
    2
    3
    4 number = 7;
    5 return number;
    6
    7 }
    8 #include <stdio.h>
    9
    10 int main(){
    11
    12 int a = 5;
    13
    14 printf("value is %d\n",foo( a));
    15
    16 }

  5. #5
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,794
    Quote Originally Posted by crystal_fox View Post
    1 int foo(int number){
    You have to read this Announcements - General Programming Boards
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. code fragment
    By mikel360 in forum C Programming
    Replies: 12
    Last Post: 05-23-2011, 12:30 PM
  2. Please explain me this C code fragment
    By stefboombastic in forum C Programming
    Replies: 6
    Last Post: 12-16-2010, 01:29 PM
  3. what is the output of this code fragment?
    By ryan_qut in forum C Programming
    Replies: 3
    Last Post: 11-13-2004, 02:05 PM
  4. Fragment of C++ code
    By nsimos81 in forum C++ Programming
    Replies: 3
    Last Post: 04-29-2003, 03:49 PM
  5. code fragment pls help
    By Damo in forum C Programming
    Replies: 2
    Last Post: 04-15-2002, 09:57 AM