I know {} are used to separate entities such as functions, classes and conditional branching, but what other use would they have here?
#import <stdio.h>
int main(void) {
{{{
printf("main\n");
}}}
return 0;
}
EDIT:
I found that it may be useful primarily for information hiding, along with nested functions. From the answers below it would seem they can be used as a marker during debugging and be removed in the release, but that this should not be endorsed.
Enclosing a code in braces { } creates an Scope.
Creating an local scope can have number of reasons like:
Allows you to reuse a variable name in enclosing scope.
Define variables in middle of function.
Creating variables anywhere except at the start of an scope was not allowed in c89, but it is allowed since c99.
Online Example Code Sample:
#include<stdio.h>
int main()
{
int i = 10;
{
int i = 5;
printf("i is [%d]\n",i);
}
printf("i is [%d]\n",i);
return 0;
}
In your example code,
the extra { & } do not serve any purpose, they are just redundant code.
As #Martin suggests in comments, since enclosing code in {{{ & }}} is just similar to { & }, it might be used as an tag/pattern for easy search.
However, Personally, I would prefer adding appropriate comment to the code with an keyword which would show up in search rather than add such redundant code.
That syntax (three curly braces in a row) doesn't mean anything special in standard C. The author of such code might use it to indicate something about the code inside, like that it's just there for debugging.
you can introduce a new scope, which then allows you to introduce new variables.... which can be useful in C89. Not too normal though, but occasionally useful.
{
int x =2 ;
printf("%d", x);
{
int y = 7;
printf("%d", y);
}
}
Extra braces gives you scope as Als mentioned. This can be used in case of Smart Pointers effectively. e.g., consider the following code in C++ (MSVC compiler)
int i = 0;
i++;
//More code follows
...
{
CComBSTR bstr("Hello");
//use this bstr in some code
.....
}
After the end braces, bstr won't be available. Furthermore, since it has gone out of scope, therefore, the destructor will also get called automatically.
Related
Are inner-scopes ever used in C, or is this similar to something like a goto statement that isn't used too much in production code? The only thing I can think of that might use it is making something volatile temporarily, for example:
int main(void)
{
int a=1;
const int b=4;
printf("a=%d, b=%d\n", a, b);
{
int b=5;
printf("a=%d, b=%d\n", a, b);
}
}
But that seems like a pretty non-practical example. How would these be used in practice?
One case when blocks are required is defining local variables in a switch statement.
switch(foo())
{
case 0:
printf("no '{}' block generally required, except...\n");
break;
case 1:
{
int n = bar();
printf("%d\n", (n + 1) * n);
}
break;
//...
}
Without the {} block, the code would not compile because case 1: expects a statement right after, and declarations are not statements in C.
(Incidentally, the block is usually required in C++, too, though for an entirely different reason, because initialization of n would be skipped by other case labels.)
Are inner-scopes ever used in C, or is this similar to something like a goto statement that isn't used too much in production code?
Not so much by themselves, but inner scopes come up naturally all the time as the bodies of control statements such as loops and conditional statements. For example, a variable declared inside the body of a loop goes out of scope at the end of each iteration of the loop and is instantiated again during the next iteration.
we don't use them very often in production code. but this one very useful when you need your variable's scope very specific.
as far our use case, suppose you are coding in production code, and you want your some of variable's scope very specific . in this circumstances, we just use block {.....} to limit variable scope.
Is it possible to put the variable declarations in an external function? After reading from Wikipedia that:
an inline function is a function upon which the compiler has been requested to perform inline expansion. In other words, the programmer has requested that the compiler insert the complete body of the function in every place that the function is called, rather than generating code to call the function in the one place it is defined.
I hypothesized that the following might work. It did not take long for the compiler to slap my fingers :(
inline void declaration(){
int a;
}
int main(){
declaration();
a=2;
return 0;
}
This may not be how it is done but if you want a basic idea of how you can think about what happens when you inline a function.
Imagine the compiler turning your code into something like this, then you see why it will not work.
int main(){
{
int a;
}
a=2;
return 0;
}
The call to declaration() is replaced by the contents of the function including brackets, thus int a; is declared in an inner scope and is not visible in the main function.
No, this is not possible.
What is possible, is to use a preprocessor directive #define:
#define VARBLOCK int a, b, c; char ca, cb, cc;
int main()
{
VARBLOCK;
a = 2;
}
This would be a bad practice. Also these would still be variables only available in the scope of function where it were placed, without values being shared.
No - as far as I'm aware an inline function must behave semantically equivalent to a non-inline function; it doesn't affect what counts as legal code. It's just an optimization.
In particular, you could have a variable called a in both functions, but they'd be separate variables on the stack.
(Even if you could do this, I'd suggest it would be a very bad idea in terms of readability.)
inline functions are usually just a function containing no more than about 4 lines and you would want the compiler to do the optimization you where talking about since it would be faster to do what the function does, rather than adding extra code.
Inline expansion is used to eliminate the time overhead when a function is called. It is typically used for functions that execute frequently.
So there's nothing special with the inline function, rather than it might be handled differently by the compiler. They don't share their stack with any other function, which would be the only way for main to use a variable that is created in a different scope.
So my tip is; write your functions, and treat them as you usally should. Then when you are done, inline the short ones that you use a lot.
And if you really wanna create a variable in another function, allocate it on the heap in the function and return a pointer that you save and then set to 2 (your case). :) Just remember to free the memory!
You can do this, though:
#include <stdio.h>
int* GetMyIntAddress(void)
{
static int blah = 0;
return &blah;
}
int main(void)
{
printf("%d\n", *GetMyIntAddress());
*GetMyIntAddress() = 123;
printf("%d\n", *GetMyIntAddress());
return 0;
}
blah will be a global variable defined in the scope of the GetMyIntAddress() function.
If you add inline to the definition of GetMyIntAddress(), you are risking to get multiple independent instances of blah if the inline function is used in different modules (e.g. included from a shared header file).
Recently I had to modify a legacy code that was compiled with a very old version of GCC (somewhere around version 2.3). Within a function, variable had to be declared before being used. I believe this is done C89 standard. This limitation is later removed.
My question is: Back then, why did they enforce this ruling? Was there any concern that could jeopardise the integrity of the software?
Variables still have to be declared before being used -- and they've never had to be declared just at the top of a function.
The C89 requirement is that a block consists of an opening {, followed by zero or more declarations, followed by zero or more statements, followed by the closing }.
For example, this is legal C89 (and, without the void, even K&R C, going back to 1978 or earlier):
int foo(void) {
int outer = 10;
{
int inner = 20;
printf("outer = %d, inner = %d\n", outer, inner);
}
printf("outer = %d, inner is not visible\n", outer);
return 0;
}
C99 loosened this, allowing declarations and statements to be mixed within a block:
int foo(void) {
int x = 10;
printf("x = %d\n", x);
int y = 20;
printf("y = %d\n", y);
return 0;
}
As for the reason for the original restriction, I think it goes back to C's ancestor languages: B, BCPL, and even Algol. It probably did make the compiler's job a bit easier. (I was thinking that it would make parsing easier, but I don't think it does; it still has to be able to distinguish whether something is a declaration or a statement without knowing in advance from the context.)
It was mainly to make compilers easier to write. If all the declarations were at the top of the function, it would be easy for the compiler to parse all the locals and determine how much stack is needed.
Of course now, compilers are a lot more mature than they were 30 years ago. So it makes sense to get rid of this restriction as it's become a nuisance to programmers.
I've come across a bit of code that contains a couple code blocks, delineated with curly braces {}. There is no line before the code blocks marking them as part of if statements, function definitions, or anything else. Just a code block floating in the middle of a function. Is there any meaning to this? gcc seems perfectly happy going through the code; I can only imagine it is some way to allow the original coder to split up blocks of functionality visually...
It creates a scope. Are there automatic variables defined inside the blocks? If so, then the scope of those variables is confined to the block. It's useful for temporary variables that you don't want polluting the rest of the function, and it's also useful when writing C89, where variable definitions must be at the start of a block.
So, instead of:
int main() {
int a = 0;
int b;
int i;
for (i = 1; i < 10; ++i) {
a += i;
}
b = a * a;
// do something with a and b
}
You could have:
int main() {
int a = 0;
{
int i;
for (i = 1; i < 10; ++i) {
a += i;
}
}
{
int b = a * a;
// do something with a and b
}
}
Obviously if you're doing this, you also have to ask yourself if the blocks wouldn't be better off as separate functions.
Standalone curly braces are used for scoping—any variables declared in a block aren't visible outside it.
If the code blocks contain local variable declarations (your description is not clear about what's inside), they may be there to limit the scope of those variables. I.e.
int i = ...;
// i is visible here
{
int j = ...;
// both i and j are visible here
}
// j went out of scope, only i is visible here
It is used to create a scope. A scope if useful to declare variables that can only be used inside this scope. For example, if a variable is declared before the braces, it can be used inside the braces of after them. At the contrary, if a variable is declared inside the braces, it can only be used inside the braces.
Hope this helps.
It usually means it was written to declare a variable part way through a larger function, but the variable only needs a very limited scope, or may even need to hide something. It is entirely legimitate - it simply introduces a block. The big issue is always "what is the correct indentation for that code".
It can also be used by pre-processors that convert some other language into generated C. The converted material is often wrapped in a block (and possibly #line directives too).
I need some help rewriting the following line in a more type safe way and rewriting it as a function, however the fact that this code is defined inside a function is making it hard for me to think of a clever way of doing it because apparently it would involve declaring several arguments.
#define CHECK(id) if(table->cells[id]) isgood[table->cells[id]-1] = 0;
where table is a struct and isgood is an int.
Straight translation (if table->cells[id] is int):
void check(int id, int*isgood) { if (id) isgood[id-1] = 0; }
Call with:
check(table->cells[id], isgood);
However, I'd rename/rework this a bit. I'd especially change the name. There is also no error checking - ie, if table->cells[id]==0, you're going to try to set isgood[-1], which would be bad.
apparently it would involve declaring
several arguments
What is wrong with that?
Why not just a function that receives table and id and does this?
void foo(TableType & t, int id)
{
if (t.cells[id])
isgood[t.cells[id]-1] = 0;
}
p.s.
It's a bad macro indeed. The name is very misleading.
p.p.s.
The whole thing is rather weird and the logic of this function escapes me. What exactly is this supposed to achieve?
If you're working in C++, I'd consider making check a member function of the table, which seems like a good candidate for a class:
class Table {
//...
public bool check(int id) {
if (this->cells[id]) {
this->isGood[id] = 0;
// the line you have, isgood[table->cells[id]-1] = 0 looks buggy:
// you treat table->cells[id] as a true/false value one line ago;
// probably not a valid array index? I'm taking a stab at what to do.
}
}
}
It is generally a good idea not to refer to variables in a macro.
First, make sure the name is meaningful. what are you checking for? And is there a side effect?
void update_valid_cells(Table& table, int id, BoolArray& validArray)
{
if(table.cells[id]==NULL) return;
validArray[id]-1=false;
}
I think C99 can qualify functions as inline so you get the speedup of no-function-call without using macros. Also, most C compilers support extensions such as __inline for this purpose.