简体   繁体   中英

Using register variables in recursion?

    #include <stdio.h>

    void main()

    {

        register int x = 0;

        if (x < 2)

        {

            x++;

            main();

        }

    }

Output:

segmentation fault

Why I am getting segmentation fault?

Register has nothing to do with this error. It is just a type of storage class.

Even without register it shows core dump.

The reason for the core dump is stack overflow becaz of recursion.

Try by using printf("%d",x) after x++ and before main();

if (x < 2)

    {

        x++;
        printf("%d",x);

        main();

    }

The reason for stack gets overflow is every time you called main() in recursion the x re initialized to 0, thus always satisfies the condition if(x < 2) and results in stack overflow.

Try to use static storage class to avoid this error.

Because 'register' is an advisory to the compiler, which compilers are free to ignore. They say "put this variable in a register, please" but it doesn't change the scope of x in your code. Which means main will be called, and then create a local variable called x reserving space on the stack, initialise it to zero, etc, etc, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM