PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] How does the negation !my_function() effect my function in C?

 October 30, 2022     buffer, c, eof, flush, negation     No comments   

Issue

This is my read_double function. Why do I have to check for !flush_buff() or what is its effect? I somehow cannot figure it out. Couldn't I just write flush_buff() and then return DBL_MIN?

double read_double(void) {
     double x;
     int c, status;

    printf("Insert double: ");
    status = scanf("%lf", &x);
    if (status == EOF || (c = getchar()) == EOF) {
        return DBL_MIN;
    }
    if (status != 1 || c != '\n' || x < DBL_MIN) {
        if (!flush_buff()) { /*What is the purpose of this?*/
            return DBL_MIN;
        }
        return DBL_MAX;
    }
    return x;
}

The flush_buff function:

int flush_buff(void) {
    int c;
    while ((c = getchar()) != '\n' && c != EOF) {}
    return c != EOF;
}

Solution

The flush_buff() function fetches characters from stdin until it encounters either a line break (\n) or end of file (EOF). If it found a line break (and not EOF), then it returns a "true" value (equal to 1).

The syntax !flush_buff() negates this return value, and thus will be false (zero) if flush_buff() stopped at a line break, or true (1) if the end of file has been reached.

In the code you posted, the value of status will be 1 if a floating point value was read successfully, 0 if a floating point value could not be read successfully, or EOF if the input stream ended without providing any input.

If status is not EOF, then an additional character c is read from the input. If this is not a newline character, or if the number provided is outside the range of positive nonzero floating point numbers, then the input is treated as invalid.

As this point, the programmer has decided — for whatever reason — that the function should return DBL_MIN if the input file ends at the current line, or DBL_MAX if the current line is terminated by a line break character. The reasoning behind this is unclear.



Answered By - r3mainer
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing