-7

I am wondering about some code i did see on the internet. I did try to google etc. but i didn't find an explanation that answered my question.

This is a example i coded.

bool exe() 
{

int ret = Geterror();//if error it returns something bigger than 0
if (ret != 0)
    return false;

ret = Geterror();//if error it returns something bigger than 0
if (ret != 0)
    return false;

return true; 
}

1) My first question is whats the different by using

if (ret != 0)
    return false;

and

if (ret != 0)
{ 
    return false;
}

2) I dont know if i think right or not, but is the line after if(ret != 0) the only line it going to run if ret is biger than 1? or does it has something to do with the posision or spacing? Sins ret = Geterror(); is going to run if ret is 0.

  • 3
    sorry. please read some very basic C++ book or tutorials. the `{ ... }` serve to group all statements that will be executed when the `if - condition is true` - if you leave them off, only the single line after `if` will be executed then – Patrick Artner Nov 18 '17 at 19:40
  • Some reading: http://en.cppreference.com/w/cpp/language/statements – user4581301 Nov 18 '17 at 19:41
  • 2
    Tutorials can be dangerous. Stick to books until you have learned enough to be able to reliably tell good tutorials from bad. [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – user4581301 Nov 18 '17 at 19:43
  • @PatrickArtner i think i just did explain my question bad. Yeah, this was the answer i was looking for -->"if you leave them off, only the single line after if will be executed then" – stackoverflowIsLoveBud Nov 18 '17 at 19:47

1 Answers1

1

To answer your first question. By doing an if statement in one line you are limited to one operation, so to speak.

if(ret != 0) return false;

Whilst using the curly brackets you are declaring a block with code operations.

if(ret != 0) {
     /* do other stuff here */
     return false;
}

There is no practical difference between using a one-liner and a block statement.

As to your second question please refer to my first line of code.

if(ret != 0) 
    return false;

is equivalent to;

if(ret != 0) return false;

The statement is delimited by using the semicolon to tell the compiler that the statement is finished, the space between is trivial.

Joel S
  • 86
  • 2
  • 3