2

I saw this piece of code. I am quite new in C, so pardon me.

The while loop below will keep looping if i < SIZE && scanf("%f",&Arr[i]) == 1.

I get the i < SIZE part but what does scanf("%f",&Arr[i]) == 1 mean? I know it is taking in the value from scanf() and assigning it to an array Arr. But what does the == 1 means?

Thanks :)

int readValue(float Arr[]) {
    int i = 0 ;
    while (i < SIZE && scanf("%f",&Arr[i]) == 1) 
        i++ ;  
    return i ;
}
Aamir
  • 5,324
  • 2
  • 30
  • 47
Lawrence Wong
  • 1,129
  • 4
  • 24
  • 40

4 Answers4

2

scanf() returns the number of assignments made, in this 1 is expected to made so if scanf() returns 1 then &Arr[i] has been successfully assigned a value. From the linked reference page the return value is described as:

Number of receiving arguments successfully assigned, or EOF if read failure occurs before the first receiving argument was assigned

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • Hi there, In this case, to end the while loop. I do a ctrl + D which is something like a EOF? – Lawrence Wong Oct 25 '12 at 13:05
  • @LawrenceWong, I _think_ the meaning of `ctrl + D` differs between platforms. In this case, you could just enter an invalid `float` value that would terminate the while (`"done"` for example). – hmjd Oct 25 '12 at 13:07
2

It probably would be clearer if there were some more parentheses in here to help keep in mind Operator Precedence:

while (i < SIZE && scanf("%f",&Arr[i]) == 1)

is the same as

while ((i < SIZE) && (scanf("%f", &Arr[i]) == 1))

So if i happens to be >= SIZE the == is irrelevant as it won't be executed at all. If i is less than SIZE then scanf() will be called and will return the number of items of the argument list successfully filled. So in your case, if this was 1 (if we got a float and put it in Arr[i]) then the conditions are met.

So you'll loop until i gets bigger than or equal to SIZE or if an invalid entry is entered into scanf()

For example if you enter the letter "h", your loop will break because that can't go into a float specificer, so scanf() will return 0.

Mike
  • 47,263
  • 29
  • 113
  • 177
1

The return value of scanf is the number of items of the argument list successfully filled.

Since there is one argument, a return value of 1 means that the call was successful. If the input could not be interpreted as a floating point number you would get a return value of 0 instead.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1

scanf returns the number of elements successfully read:

From man page:

...functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

So if input was successful for a single float value, scanf() will return 1 and condition will be true in the while loop for second part of the condition.

P.P
  • 117,907
  • 20
  • 175
  • 238