2

I don't have much experience in C++ programming. I'm getting this error

'z' does not name a type!!!

which I have't seen in MATLAB or python... What's wrong??? It is so simple!!!

float x=10; float y=50; float z;
z=x*y;

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
}
1
  • float z=x*y; will work
    – Juraj
    Commented Apr 25, 2019 at 5:44

1 Answer 1

5

You cannot put an expression statement outside a function. Only the variable declarations can be placed outside functions (and those variables are called globals/global variables).

Try the following:

float x=10; float y=50; float z;


void setup() {
  // put your setup code here, to run once:
  z=x*y;
}

void loop() {
  // put your main code here, to run repeatedly:
}

Update

What even is easier and also works (thanks to Ruslan and Juraj):

float x=10; float y=50; float z=x*y;

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
}
4
  • Thank you. pretty much basic thing that I didn't know about C++.
    – 2012User
    Commented Apr 24, 2019 at 16:18
  • 1
    You can put an expression outside a function (e.g. float z=x*y; does have an expression x*y in it, and may appear in namespace scope). What you can't put there is an expression statement (or any other type of statements).
    – Ruslan
    Commented Apr 24, 2019 at 17:28
  • @Ruslan Thanks for the clarification; I added the word statement in my answer. Commented Apr 24, 2019 at 21:25
  • and float z=x*y;
    – Juraj
    Commented Apr 25, 2019 at 5:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.