register variables

here the scanf function gives an error saying that address of a and b required.y is it so?

1
2
3
4
5
6
7
8
#include<stdio.h>
int main(){
    register a,b,x;
    scanf("%d %d",&a,&b);
    x=a+~b;
    printf("%d",x);
    return 0;
}
closed account (GhqjLyTq)
The register keyword tells the compiler to try to store the variables in the registers instead of RAM. A pointer contains the address of something in RAM. The variables are in the registers, not RAM, so they don't have an address, and therefore you can't have a pointer to them.

Try changing register to int.
Last edited on
thnx
According to what I've found, most of the newer compilers ignore register and decide on its own where the variable is to be stored. The furthest back I found that kind of remark was 2010 so I don't know if it is even worth messing with register or not now.
To access a specific location you need address of that location. The Problem was in the declaration. "register" tells to store the value in the register while "int" is the type of value to be stored. Here is the Working Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

int main()
{
    register int a, b, x;

    scanf("%d %d",&a,&b);
    
    x = a + b;

    printf("\nResult is: %d", x);
    
    return 0;
}
Here is an older quote (2008) concerning registers after a beginner asked for a good example of using register that I think explains what I was trying to say better:

There is no good example of register usage when using modern compilers (read: last 10+ years) because it almost never does any good and can do some bad. When you use register, you are telling the compiler "I know how to optimize my code better than you do" which is almost never the case. One of three things can happen when you use register:

--The compiler ignores it, this is most likely. In this case the only harm is that you cannot take the address of the variable in the code.
--The compiler honors your request and as a result the code runs slower.
--The compiler honors your request and the code runs faster, this is the least likely scenario.
Even if one compiler produces better code when you use register, there is no reason to believe another will do the same. If you have some critical code that the compiler is not optimizing well enough your best bet is probably to use assembler for that part anyway but of course do the appropriate profiling to verify the generated code is really a problem first.


http://stackoverflow.com/questions/314994/whats-a-good-example-of-register-variable-usage-in-c
Topic archived. No new replies allowed.