+ 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
8 Respuestas
+ 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;
}
+ 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
+ 2
Jesse Becker as Fermi suggested, you need to use a function to reassign value to a variable.
+ 1
Nagendra Are you sure about that? I never heard of such a rule in any programming language
+ 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.
0
Please post your full code. The code you posted doesn't have 14 lines
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...!!!
0
etou.... you have two b in one code ??? ( b=21 & b=5)