1

I'm now learning C and am using a fairly good book to study from (it makes things pretty easy to understand anyhow...) but I came across something that I can't seem to wrap my head around and would like an explanation of what this particular line of code is 'doing'...

here is the function:

int yes_no(char *question)
{
   char answer[3];
   printf("%s? (y/n): ", question);
   fgets(answer, 3, stdin);
   return answer[0] == 'y';
}

So from what I understand of C programming so far, this function is supposed to return an int, it takes a string created somewhere outside this function, adds a "? (y/n): " to the end of it and prints that question to the screen, then allows the user to input yes or no and stores that in an array called "answer".....but this looks like it will return a char... or something.... not an int....and why is there an == 'y' in the return line? For the life of me I can't figure out what the return line of this function is doing. Some help would be muchas gracias.

pamphlet
  • 2,054
  • 1
  • 17
  • 27

4 Answers4

2

but this looks like it will return a char... or something.... not an int

No, but that wouldn't be a problem either. Integral types can be implicitly converted one to another, so returning a char from a function that's declared to return an int is perfectly fine.

Apart from that, comparison operators in C yield an int -- one if the premissa in the comparison is true, and zero otherwise. This function basically tests if the first character of the entered string is a 'y'.

1

Return answer[0] == 'y';

will actually return a int, a 1 if the answer starts with 'y' and a 0 if the answer was anything else that did not start with a 'y'

orgtigger
  • 3,914
  • 1
  • 20
  • 22
1

Seeing your recent edit, what you are returning is the result of the comparison answer[0]=="y", which is in C an integer.

++++++++++

Your function receives a parameter, a pointer to a char which we can assume is a string.

Then you print that parameter followed by (y/n) and wait for some user input in stdin.

When you get that input, you check the first character of it, if it is a Y you return 1~true and if it's not you return 0~false

Ruben Serrate
  • 2,724
  • 1
  • 17
  • 21
  • Ok I see, I'm just still new at this and was only used to seeing comparisons in 'if' statements. I assumed that was the only place you would use them. I didn't know that you could still get a 1 or 0 returned from them anywhere you use them. That's good to know! Thanks for the tip! – Jason Sturgeon Sep 27 '13 at 18:23
0

answer[0] == 'y' is evaluated to a bool, all bools will be promoted to int, and give you 1 or 0 as the return value. check this: Can I assume (bool)true == (int)1 for any C++ compiler?

Community
  • 1
  • 1
Zac Wrangler
  • 1,445
  • 9
  • 8