Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax confusion regarding C++ while loops

Tags:

c++

I recently started to learn C++ and I have a question regarding the syntax of an exercise given in our lecture about the accuracy when we declare different types of variables, in this case float and double.

#include <iostream>
using namespace std ;

int main()
{
    // Accuracy test with float
    float eps_f = 1.0 ;
    while (float(1.0 + eps_f) != 1.0)
    eps_f /= 2.0 ;
    cout << "Resolving capacity float approximately: " << 2*eps_f << endl ;
    
     // Accuracy test with double
    double eps_d = 1.0 ;
    while (1.0 + eps_d != 1.0)
    eps_d /= 2.0 ;
    cout << "Resolving capacity double approximately : " << 2*eps_d << endl ;
}

So what I don't understand is what is the point of while here? What is happening?

like image 706
imbAF Avatar asked Apr 24 '26 03:04

imbAF


1 Answers

In C++, indentation does not affect the flow of a program, but it DOES affect the readability.

This can be better written as:

#include <iostream>
using namespace std ;

int main()
{
    // Accuracy test with float
    float eps_f = 1.0 ;
    while (float(1.0 + eps_f) != 1.0)
    {
        eps_f /= 2.0 ;
    }
    cout << "Resolving capacity float approximately: " << 2*eps_f << endl ;
    
     // Accuracy test with double
    double eps_d = 1.0 ;
    while (1.0 + eps_d != 1.0)
    {
        eps_d /= 2.0 ;
    } 
    cout << "Resolving capacity double approximately : " << 2*eps_d << endl ;
}

A while loop will operate on the next statement. If braces are used, it will treat the block enclosed in the braces as a statement. Otherwise, it will only use the next statement.

The following snippets are identical:

while(1) 
{
    do_stuff();
}
 do_other_stuff();
while(1) do_stuff(); do_other_stuff();
while(1) 
do_stuff(); 
do_other_stuff();
like image 177
blackbrandt Avatar answered Apr 26 '26 18:04

blackbrandt