-5

I am trying to show the a number that I have specified in a program, but recieve the following error:

main.c(23): error #2048: Undeclared identifier 'number'.

#include <stdio.h>



int main()

{

 {

int number = 32 ;

}

printf("integer is %d \n", number );

    return 0;
}

I'm aware the solution to this must be very simple to some users, however i'm following instructions from a book and as far as I know i'm following to the letter.

Please any help would be greatly appreciated.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

4 Answers4

0

Braces {} in C is used to introduce a block, and that block is it's own scope, variables declared in that block is local to that block and nested blocks inside of it.

When you declare number in its own block, the variable is only declared in that block, not the outer block. So the solution is very simple: Remove the braces and put the variable in the outer block:

int main()
{
    int number = 32 ;

    printf("integer is %d \n", number );

    return 0;
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Your problem is scoping:

int main()
{
   {       
      int number = 32 ;     <== Number enters scope here
   }                        <== Number leaves scope here

   printf("integer is %d \n", number );  <== Number is out of scope scope here

   return 0;
}

What happens within brackets, stays within brackets.

(weeeell, it sounds better than "the first rule of scoping is that you don't talk about scoping" ;-)

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
0

The declaration of number is enclosed into it's own block with curly braces, thus having the scope in this block only, so trying to access it outside of that block yielding the error. The solution is to move the declaration outside of that block (remove the extra curly braces around it ),

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
0

Please indent your code. You declared and initialized an integer variable only living in inner braces. Therefore, "number" is destroyed and does not exist when printf instruction is reached.

This following code works as you expect:

int main()
{
   int number = 32 ;
   printf("integer is %d \n", number );
   return 0;
}
Richard Dally
  • 1,432
  • 2
  • 21
  • 38