Problem with variables, C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Problem with variables, C++

This is the intro to my code. It's pulling an error: "..\Playground\:14:1: error: 'b' does not name a type b = 5 ; ^" By the way, line 14 is the line I state 'b = 5; ' What did I do wrong? I did almost exactly what the example said to do. #include <iostream> using namespace std; int a = 45; //declare variable a int b = 21; //write variable b = 21 b = 5 ; int sum = a + b; //write variable sum = a + b

16th Apr 2019, 3:23 AM
Jesse
Jesse - avatar
8 Answers
+ 7
Mmm, it doesn't seem like your program contains a main function. That could be the problem. You can declare variables a and b outside main, but any subsequent operation on the variables have to proceed within a function which can be executed. #include <iostream> using namespace std; int main() { int a = 45; //declare variable a int b = 21; //write variable b = 21 b = 5 ; int sum = a + b; //write variable sum = a + b cout << sum; }
16th Apr 2019, 4:17 AM
Fermi
Fermi - avatar
+ 4
Thanks guys I had a main function but that wasn't where the problem was. Now I understand I can only redefine a variable inside a function. Thanks
16th Apr 2019, 2:36 PM
Jesse
Jesse - avatar
+ 2
Jesse Becker as Fermi suggested, you need to use a function to reassign value to a variable.
16th Apr 2019, 7:35 AM
Sahil Soma
Sahil Soma - avatar
+ 1
Nagendra Are you sure about that? I never heard of such a rule in any programming language
16th Apr 2019, 6:44 AM
Anna
Anna - avatar
+ 1
Zierol Channel Yes, I was just testing out what the lesson told me about how to redefine a variable. I'm not making anything useful with my code.
17th Apr 2019, 11:02 PM
Jesse
Jesse - avatar
0
Please post your full code. The code you posted doesn't have 14 lines
16th Apr 2019, 4:53 AM
Anna
Anna - avatar
0
U can reassign value to variable only after defining all local variables. That means b=5; not allowed before int sum =a+b; So, comment //b=5; Then u will not get my compilation error. But, sum =21+45=66 Not sure...!!!
16th Apr 2019, 5:52 AM
Kuri
Kuri - avatar
0
etou.... you have two b in one code ??? ( b=21 & b=5)
17th Apr 2019, 5:56 AM
Zierol Channel
Zierol Channel - avatar