-1

I'm a newbie here and I just started college. We are learning C++ and I find it a little bit difficult, because of the way the teachers explain. Yesterday we did a task that says to create a program, which finds greatest common divisor of 2 numbers. So, the teacher started writing the code, but the explanation wasn't enough for me and I really need some help right now. (I putted comments on the things I don't understand.) Here is the code:

#include <iostream>
#include <cmath>

using namespace std;

int main(){

    int a, b;
    cout << "a = ";
    cin >> a;
    cout << "b = ";
    cin >> b;
    cout << "GCD (" << a << ", " << b << ") is ";

    if (a != 0 && b != 0){
        size_t min = abs(a) < abs(b) ? abs(a) : abs(b); //What's that after (?)?
        size_t max = abs(a) > abs(b) ? abs(a) : abs(b);
        size_t diff = max - min; //What is that variable used for?

        while (diff > 0)
        {
            min = diff < min ? diff : min;
            max = diff > min ? diff : min;
            diff = max - min;
        }
        cout << min << endl;
    }
    else{
        if (a != 0 || b != 0)
            cout << (a>b ? a : b) << endl;
        else
            cout << "not possible!!!\n";
    }
    system("pause");
    return 0;
}

QUESTION: When should I put {} on if's, while's etc.?

Boyan Petrov
  • 105
  • 4
  • 5
    "When should I put {} on if's, while's etc.?" - always. –  Nov 14 '18 at 14:12
  • 1) What book are you using to learn C++ from, alongside the lectures? If you aren't using any, consider picking one from [this list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). 2) What, exactly, you find unclear about the explanations given to you? What were those explanations? If you don't give such information to us, we might just repeat what your lecturer already said, which would help no-one. – Algirdas Preidžius Nov 14 '18 at 14:13
  • The first commented expression is called the 'conditional operator'. "Expression1 ? Expression2 : Expression3" – 2785528 Nov 14 '18 at 14:18
  • 3
    tbh i think the best you can do is ask your prof or co-students. Working together with others and direct tutoring is extremely important and valuable and cannot be replaced by online Q&As – 463035818_is_not_an_ai Nov 14 '18 at 14:20
  • 1
    The correct person to ask is your teacher. If they don't realise they are assuming students know certain language constructs, they won't adjust their approach to teaching the course. – paddy Nov 14 '18 at 14:20
  • ...moreover we cannot know what was your teachers intention when presenting you this code. If they didnt get the message across you should let them know. However, all that is of course not a reason to not ask questions here ;) – 463035818_is_not_an_ai Nov 14 '18 at 14:22
  • 1
    Beware that this code shows a lot of bad habits. My impression is that your teacher may be bad at what they teach... – François Andrieux Nov 14 '18 at 14:23
  • @FrançoisAndrieux For that matter, it's a terrible implementation of the Euclidean algorithm. – John Perry Nov 14 '18 at 14:36
  • @FrançoisAndrieux i would say it depends. eg. if the lesson was about using the ternary then the code has something, if the lesson was about using standard functions when applicable then the code is a fail ;) – 463035818_is_not_an_ai Nov 14 '18 at 14:37
  • @Damien It is equivalent to the Euclidean algorithm; it just uses repeated subtraction in place of division. Division _is_ repeated subtraction. – John Perry Nov 14 '18 at 18:00

6 Answers6

1

This is the syntax for an if-statement

if ( condition ) statement-true else statement-false

statement-true is either one statement or a block of statements in {...}

So you can use if without {...} if there is only one line. But it is better to always use {...}.

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
  • 2
    "_is either one statement or a block of statements in `{...}`_" Technically speaking, it is always a single statement. It's just `{...}` is a compound statement. – Algirdas Preidžius Nov 14 '18 at 14:17
1

It is necessary when you need more that one line/statement to be executed by the if/else/while. Valid examples:

if (a != 0 || b != 0)
    cout << (a>b ? a : b) << endl;

if (a != 0 || b != 0) cout << (a>b ? a : b) << endl;

if (a != 0 || b != 0) {
    cout << (a>b ? a : b) << endl;
    a++; }

If you did:

if (a != 0 || b != 0) 
    cout << (a>b ? a : b) << endl;
    a++; 

The the a++; would be executed regardless of the if condition.

Some programmers like to use {} even for single statements because they believe it leads to more usable and maintainable code. I do not belong to that group but I can see the arguments on either side.

SunKnight0
  • 3,331
  • 1
  • 10
  • 8
1
size_t min = abs(a) < abs(b) ? abs(a) : abs(b); //What's that after (?)?

C and C++ have a construct that is similar to an if-else statement. This line basically says that if abs(a) is smaller than abs(b), then min should take the value of abs(a); otherwise, it should take the value of abs(b).

size_t diff = max - min; //What is that variable used for?

It's not clear what you mean here. If you mean diff, the code essentially uses it in the subsequent while loop to perform division by repeated subtraction. This is a very strange thing to do, especially because it is so inefficient, and division would have been more compact and efficient in the loop. It's even stranger given that earlier the author uses ?: (which you asked about); that construction is used mainly because it's more compact and efficient than an if-else statement, but this is rather strange code, anyway.

When should I put {} on if's, while's etc.?

You should do it by default. You don't have to do it if only one statement is to be performed when the condition is true (resp. false) but people usually do as a matter of good style and to assist readability. For instance, this code

if (a != 0 || b != 0)
    cout << (a>b ? a : b) << endl;
else
    cout << "not possible!!!\n";

could just as easily be

if (a != 0 || b != 0) {
    cout << (a>b ? a : b) << endl;
} else {
    cout << "not possible!!!\n";
}

...and a lot of instructors would actually require the latter from learners.

John Perry
  • 2,497
  • 2
  • 19
  • 28
0

In addition to the other answers:

//What's that after (?)?
foo ? bar : qux;

Is the use of the ternary operator.

If foo is true the expression evaluates to bar else it evaluates to qux.

Swordfish
  • 12,971
  • 3
  • 21
  • 43
0

Just adding my two cents...

This

if (a != 0 || b != 0)
        cout << (a>b ? a : b) << endl;

is equivalent to

if (a != 0 || b != 0) {
        cout << (a>b ? a : b) << endl;
}

The big difference comes when you realize that code is not something static that you write once and then never change again. Lets change the example a little bit (intentially weird intendation)

if ( x )           // (I)
    y = a;
    z = b;

is not the same as

if ( x ) {         // (II)
    y = a;
    z = b;
}

Using brackets allows you to focus on only the part you care about. Consider that you later decide to swap the two lines, then

if ( x ) {
    z = b;
    y = a;
}

is still ok (its the same as (II), apart from swapping the two instructions), while

if ( x )
    z = b;
    y = a;

is doing something completely different as the version above (I). If you use the brackets you dont need to care whether those two lines are inside a if block. To decide if you can swap them you need to look at nothing more than those two lines. This is not the case if you do not use the brackets. This may seem like a minor thing, though I have seen countless bugs caused by not putting brackets where there could be some.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

For 1 line of code following if, else, else if, while, etc

if (<some condition>)
    //1 line of code`

and

if (<some condition>)
{
   //1 line of code
}

...are equivalent and it is up to you (personal style,developer choice,readability etc.) to make that decision.

For > 1 line of code following if, else, else if, while, etc {} is required if you want code completely scoped to the condition statement. It is up to you the developer to make sure to scope these lines of code (i.e. the compiler will not warn you about this.. it will not know if the intent was 1 line or multiple lines).

So an example

if(<some condition>)
{
    //line of code 1
    //line of code 2
}

the compiler will let you do this...

if(<some condition>)
    // line of code 1
    // line of code 2

but //line of code 2 has no relation to the if condition since it was not scoped with {} and will be executed regardless of the if statement condition.

static_cast
  • 1,174
  • 1
  • 15
  • 21