This is weird...

I was just reading through the Linux kernel source (I just wanted to read through some of it, to learn) and I noticed something that Linus Torvalds does that looked a little weird to me. So I tried it and it compiles:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>

int main() {
    {
        printf("Hello, world!");
    }
    char buf[512];
    {
        fgets(buf, 512, stdin);
    }
    {
        return 0;
    }
}


What? We can make blocks that have no function but to provide easy reading? I didn't know that!

Here's the actual snippet, from panic.c:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#ifdef __sparc__
	{
		extern int stop_a_enabled;
		/* Make sure the user can actually press Stop-A (L1-A) */
		stop_a_enabled = 1;
		printk(KERN_EMERG "Press Stop-A (L1-A) to return to the boot prom\n");
	}
#endif
#if defined(CONFIG_S390)
	{
		unsigned long caller;

		caller = (unsigned long)__builtin_return_address(0);
		disabled_wait(caller);
	}
#endif
	local_irq_enable();
	for (i = 0; ; ) {
		touch_softlockup_watchdog();
		i += panic_blink(i);
		mdelay(1);
		i++;
	}
	bust_spinlocks(0);


Can anyone shed some light on this? Is there any scoping? It seems that things within the brackets can access things without.

Edit: This doesn't compile:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>

int main() {
    {
        printf("Hello, world!");
        char buf[512];
    }
    {
        fgets(buf, 512, stdin);
    }
    {
        return 0;
    }
}


So obviously there is scoping. But can someone explain what the purpose of this is? I didn't know you could do it; I'm going to start using that -- it makes for easier reading imo.
Last edited on
That makes smaller scope chunks
eg:
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
    {
       int x;
       //use x
    } // x out of scope

    {
          float *x; // this is a completely different variable respect to the prevoious 'x'
          // use x
    }
}
Ohhh. Thanks

What about this:
void warn_slowpath_fmt(const char *file, int line, const char *fmt, ...)
What is the purpose of the "..."?

I'm glad I decided to actually read through the source. Alot of it is far too complicated for me to really understand but I'm still learning from it, so that's good.
Last edited on
It's called ellipsis, that allows you to have any number of argument of any type
( see http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_C.2C_Objective-C.2C_C.2B.2B.2C_and_D )
printf works with that http://www.cplusplus.com/reference/clibrary/cstdio/printf/

Notice, variadic functions ( functions which have an ellipsis ) aren't really good -they don't check the argument types- but C++0x will introduce variadic templates which will be better
Last edited on
Ohhhh... I was wondering about that. Thanks :)
Topic archived. No new replies allowed.