How do I set a global variable inside a function

First off, please post complete code. And please use code tags

type
** **[code]** **

paste your code after that
type
** **[code]** **
after the pasted code

A global variable is a variable that is not declared inside any function. So declare alarm somewhere before setup if you need it to be global; that however is more than likely not necessary.

The problem in the below code is that alarm is only known inside the if block

    if(distance < x){
      const int alarm = 1;
    }

and that is why alarm is not known when you test it with below code

  if (alarm > 0) {

You can simply declare the variable in the function where you need it

void somefunc()
{
  ...
  ...

  // your variable here
  int alarm = 0;

  ...
  ...


  // put your setup code here, to run once:
  if (distance < x) {
    alarm = 1;
  }
  if (alarm > 0) {
    tone(8, 850, 500);
    delay(600);
  }
}

Also, you can not use the 'const' keyword because that would make the variable read-only.