Making the scope of a variable global?

When I define a variable, how do I make it global so other functions can access it?
You generally want to avoid this as much as possible. One of the fundamental guidelines is to keep the scope of variables as small as possible. If another function needs a var, it's best to pass it as a parameter. Using globals everywhere leads to very messy, unorganized, and hard to maintain code.

But to actually answer your question -- just declare it outside of any function. Then every function in the .cpp file will have access to it:

1
2
3
4
5
6
7
8
9
10
11
int aglobalvar;

void foo()
{
  aglobalvar = 5;
}

void bar()
{
  aglobalvar = 6;
}


If you want it visible across multiple cpp files, that gets trickier, but is even messier practice.
Thanks.

1
2
3
chess.cpp:76:20: warning: multi-character character constant
chess.cpp: In function ‘void redrawBoard()’:
chess.cpp:76: warning: overflow in implicit constant conversion


Uhm, why exactly is this happening...

1
2
3
4
5
6
7
8
9
void redrawBoard(void)
{
        char redraw[] = { '0x1b', '2', 'j' };
        cout << redraw;
        for(int i=0;i<8;i++)
        {
                drawCell(i);
        }
}
Last edited on
if you're using C-style strings (char arrays), you need to have a null terminator to mark the end of the string.

Usually it's best to make strings with the double quotes, rather than doing single quotes inside of braces like you're doing.

Also single quotes around multiple characters ('0x1B') is not what you want. There is rarely a reason to do that. I'm not sure what you were trying to do there, but it was probably one of these:

1
2
3
char redraw[] = "\x1b" "2j";  // <--- this will be the character code 1B (escape) followed by "2j"
// or
char redraw[] = "0x1b2j";  // <--- this will be 0x1b2j as seen 


double quotes automatically puts the null terminator at the end, so you don't have to worry about it.
Why not just?

1
2
3
4
5
6
7
8
9
10
11
12
#include <string>

void redrawBoard(void)
{
        string redraw[] = { "0x1b", "2", "j" };
        cout << redraw;
        for(int i=0;i<8;i++)
        {
                drawCell(i);
        }
}
@npath it would display it as a literal string, I'm trying to use an escape sequence so it wouldn't work like that.

@Disch I'm trying to make an escape sequence work so it will clear the screen (Taken directly from ANSI escape code page on Wikipedia - http://en.wikipedia.org/wiki/ANSI_escape_code), although it works now, it doesn't work :|
Clear the screen
http://www.cplusplus.com/forum/articles/10515/

"Why not use the ANSI Terminal escapes controls ?"
http://www.cplusplus.com/forum/articles/10515/page1.html#msg52663

ANSI terminal fun:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// vt100.h
/*
 ----------------------------------------------
 Terminal macros to use in C++ console programs
 ----------------------------------------------

 Use the following macros in your C++ cout statements to manipulate the
 video display. Most systems emulate either VT100 terminals or the ANSI
 terminal protocol. If yours does not, these won't work until you find
 an ANSI terminal driver.

 The following macros are practically guaranteed to work:
   clear_screen
   audible_bell
   goto_xy()
   move_to()
   default_attributes
   set_reverse()
   set_colors()
   finalize

 The least likely to work are
   show_cursor()
   set_italic()

 .............................................................................
 Example usage:

   cout << clear_screen
        << goto_xy( 10, 2 )
        << "Hello";

 To terminate your program, your code should look like this:

   cout << finalize;
   return EXIT_SUCCESS;

 .............................................................................
 T H E   M A C R O S

   cout << reset                       Restores the terminal to it's original
                                       state.
                                       You probably don't want to use this.

   cout << clear_screen                Clear the entire screen.
        << clear_to_bos                Clear from the top of the screen.
        << clear_to_eos                Clear to the bottom of the screen.

   cout << clear_to_eol                Clear to the end of the line.
        << clear_to_bol                Clear to the beginning of the line.
        << clear_line                  Clear the entire line.

   cout << visual_bell                 Blinks the screen (unreliable).
        << audible_bell                Sounds the speaker beep.

   cout << show_cursor( TRUE )         Make the cursor visible (default)
        << show_cursor( FALSE )        Make the cursor invisible

   cout << goto_xy( x, y )             Move the cursor to coordinate (x, y),
                                       or (column x, line y), where (1, 1)
                                       is the upper-left corner of the screen.
        << move_to( line, column )     Same.

   cout << cursor_up(    count )       Move the cursor "count" characters
        << cursor_down(  count )       (or lines) from its current position.
        << cursor_left(  count )
        << cursor_right( count )

   cout << set_scrolling_region( top, bottom )
                                       Set the lines in the range [top,bottom]
                                       to be those that scroll.
        << scroll_up(   count )        Scroll the region up or down "count"
        << scroll_down( count )        lines.

   cout << insert_line( count )        Insert or delete "count" items.
        << delete_line( count )        Always inserts blanks.
        << insert_char( count )        The result is affected if you change
        << delete_char( count )        the scroll region.

   cout << default_attributes          Reset so that the cursor attributes are
                                       the default (no bold, underline, etc.
                                       and colors are VT_DEFAULT).
        << set_bold( bool )            Bold text.
        << set_italic( bool )          Italic text.
        << set_underline( bool )       Underline text.
        << set_reverse( bool )         Reverse or invert the text colors.
        << set_attributes( bold, italic, underline, reverse )
                                       Set all four text attributes at once
                                       without affecting the color attributes.
        << set_colors( fg, bg )        The colors are
                                         VT_BLACK    VT_YELLOW    VT_CYAN
                                         VT_RED      VT_BLUE      VT_WHITE
                                         VT_GREEN    VT_MAGENTA   VT_DEFAULT

   cout << finalize                    Do this before your program ends.
                                       (Alias for default_attributes.)

 .............................................................................
 Lastly

   All this does is drive some basic functionality of a VT100/ANSI terminal.
   Notibly, it lacks:
    * The ability to tell you where the cursor is (so you must remember!)
    * The ability to tell you the size of the terminal screen.
      (You can use "stty size" at the command prompt to find out.)
    * The ability to get just one character from the keyboard.
      This takes some jumping through a few hoops. If you want to do some more
      advanced stuff than what is presented here, consider using the ncurses
      library (type "man ncurses" at the prompt).
      (Here at RU, you'll have to include </usr/local/include/ncurses.h>
      instead of just plain old <ncurses.h> to make curses work. Don't forget
      to compile with "g++ ... -lncurses"!)
   If you're interested in this kind of junk, type "man screen" at the prompt.

 Enjoy!

 --Michael Thomas Greer

 */

#ifndef VT100_MACRO_H
#define VT100_MACRO_H

#ifndef TRUE
#define TRUE (1)
#endif
#ifndef FALSE
#define FALSE (0)
#endif

#define VT_BLACK    0
#define VT_RED      1
#define VT_GREEN    2
#define VT_YELLOW   3
#define VT_BLUE     4
#define VT_MAGENTA  5
#define VT_CYAN     6
#define VT_WHITE    7
#define VT_DEFAULT  9

#define reset "\33c"

#define clear_screen "\33[2J"
#define clear_to_bos "\33[1J"
#define clear_to_eos "\33[J"

#define clear_line   "\33[2K"
#define clear_to_bol "\33[1K"
#define clear_to_eol "\33[K"

#define visual_bell  "\33g"
#define audible_bell "\a"

#define show_cursor( v ) ((v) ? "\33\67p" : "\33\66p")

#define goto_xy( x, y ) "\33[" << y << ";" << x << "H"
#define move_to( y, x ) "\33[" << y << ";" << x << "f"

#define cursor_up(    count ) "\33[" << count << "A"
#define cursor_down(  count ) "\33[" << count << "B"
#define cursor_right( count ) "\33[" << count << "C"
#define cursor_left(  count ) "\33[" << count << "D"

#define set_scrolling_region( top, bottom ) "\33[" << top << ";" << bottom << "r"

#define scroll_up(   count ) "\33[" << count << "S"
#define scroll_down( count ) "\33[" << count << "T"

#define insert_line( count ) "\33[" << count << "L"
#define delete_line( count ) "\33[" << count << "M"

#define insert_char( count ) "\33[" << count << "@"
#define delete_char( count ) "\33[" << count << "P"

static bool is_b = FALSE;
static bool is_i = FALSE;
static bool is_u = FALSE;
static bool is_r = FALSE;
static int  fg_c = VT_DEFAULT;
static int  bg_c = VT_DEFAULT;

#define default_attributes "\33[0m"

// these four following are not meant to be used externally
#define set_b( b ) ((is_b = b) ? "\33[1m" : "")
#define set_i( i ) ((is_i = i) ? "\33[3m" : "")
#define set_u( u ) ((is_u = u) ? "\33[4m" : "")
#define set_r( r ) ((is_r = r) ? "\33[7m" : "")

#define set_colors( fg, bg ) "\33[3" << (fg_c = fg) << ";4" << (bg_c = bg) << "m"

#define set_attributes( b, i, u, r ) set_b( b ) << set_i( i ) << set_u( u ) << set_r( r ) << set_colors( fg_c, bg_c )

#define set_bold(      b ) default_attributes << set_attributes( b, is_i, is_u, is_r )
#define set_italic(    i ) default_attributes << set_attributes( is_b, i, is_u, is_r )
#define set_underline( u ) default_attributes << set_attributes( is_b, is_i, u, is_r )
#define set_reverse(   r ) default_attributes << set_attributes( is_b, is_i, is_u, r )

#define finalize default_attributes

#endif

// end vt100.h 

Enjoy!

[edit]
Oh yeah, the code char cls[] = { '\x1B', '[', '2', 'J', '\0' };
is the same as char cls[] = "\x1B[2J";
Also remember to be very careful with ANSI escape sequences -- they must be emitted exactly or they will fail and/or do something obnoxious to your terminal.
Last edited on
@Disch I'm trying to make an escape sequence work so it will clear the screen (Taken directly from ANSI escape code page on Wikipedia - http://en.wikipedia.org/wiki/ANSI_escape_code), although it works now, it doesn't work :|


Why do so many newbies want to do this? What is the appeal?

Don't bother clearing the screen. It's more of a hassle than it's worth. Don't bother with anything fancy on the console. That's not really what the console is made for, and it's typically a lot more complicated than it seems.

More than likely the only thing you'll need the console for is learning the basics (if even that!), and you'll leave it afterwards for other APIs and programming mediums. You might come back to it to make some quickie CLI programs, but in those you probably won't need any fancy-pants stuff anyway. It's not worth the time, effort and additional workload to learn all these things you'll never use.

Then again I'm kind of "anti console" so my opinions are heavily biased. Take that for what it's worth.

</rant>
IMHO, because people want to create "nice" interfaces, and all GUIs have a steep learning curve.
Topic archived. No new replies allowed.