Setting values inside namespace/structs

Why is it possible to do following:

1
2
3
4
5
namespace G {
 
    int a = 20;
    
};



But not:

1
2
3
4
5
6
namespace G {
 
    timeval timeout;      
    timeout.tv_sec = 10;
    
};


Last edited on
This
 
int a = 20;
is a combined declaration and definition (or initialization, since it's data).

This
 
timeout.tv_sec = 10;
is a statement. It doesn't add a new name that's referenceable from other locations, it just executes something; an assignment expression in this case. It's invalid for the same reason an if statement is invalid outside of a function.
Last edited on
In C99 (and C++20) you can do:
 
timeval timeout = { .tv_sec = 20 };


In the mean time, you may assume the definition is:
1
2
3
4
struct timeval {
    time_t tv_sec;
    suseconds_t tv_usec;
};

https://pubs.opengroup.org/onlinepubs/007908775/xsh/systime.h.html

You can then write code like:
 
timeval timeout{ 0, 20 };
Last edited on
Topic archived. No new replies allowed.