#What is the difference bro?

29 messages · Page 1 of 1 (latest)

main loom
#

So I started learning C++ yesterday and I came across this concept: If, else if and else and Switch. What is the difference in this code?

include <iostream>

using namespace std;

int main() {
int age;
cout<<"Enter your age: "<<endl;
cin>>age;

 if (age==15) {
    cout<<"You are 15";
 }
 else if (age==6) {
    cout<<"You are 6";
  }
 else {
     cout<<"You are neither 15 nor 6.";
 }
return 0;

}

and this:

include <iostream>

using namespace std;

int main() {
int age;
cout<<"Enter your age: "<<endl;
cin>>age;

switch (age)
{
case 15:
cout<<"You are 15";
break;
case 6:
cout<<"You are 6";
break;
default:
cout<<"You are neither 15 nor 6";
break;
}
return 0;
}

brazen minnow
#

don't do using namespace std;

#

The two snippets you posted are more or less the same (and probably compile down to almost the same instructions)

#

the main difference is that ifs are ifs and switch-statements use a jump table to know in advance where they have to go (based on the value)

#

buuuut the compiler might use one or more jump tables to actually get to the correct location (or it might just convert one into the other)

faint stirrup
#

Ya switch is fast it's basically a go-to?

sharp granite
main loom
sharp granite
#

bcz standart lib contains alot of functions

brazen minnow
sharp granite
#

that might get identical

main loom
sharp granite
#

match case

brazen minnow
#

match is not a switch statement

sharp granite
#

..

brazen minnow
#

match in Python is for structural pattern matching 🙂

sharp granite
#

well similar behaviour ?

brazen minnow
#

but the actual use-case is pattern matching

sharp granite
#

right!!

main loom
brazen minnow
main loom
#

@brazen minnow For learning C++ basics, like the functions or the loops, using namespace std; is fine right?

#

its because i am a beginner and do not wish making large scale games soon

#

i want to learn the fundamentals first

main loom
#

@brazen minnow please reply

brazen minnow
#

Will it kill you to have 5 extra characters in your code?

main loom
brazen minnow
#

Yes it's better to explicitly have std:: instead of using namespace std;