I have a doubt regarding structs and if statements in C++
For the sake of simplicity, I have created a sample code to explain my intention
int var = 10
struct example{
int a;
int b;
if(var > 8){
int c;
}
};
I have a codebase which uses similar kind of code as above. Commenting out the if portion does not give any errors.
My question is
Could if statements be put in struct declarations?
If not, what is the possible remedy for this, since if statment is mandatory.
Note: I cannot use #if,#else directives nor std::optional or other standard libraries to mitigate this, so please help me find another solution.
No you can't use if statement inside your struct or class definition. Instead, for condition declaration, you can use #if directive.
#define var 10
struct example {
int a;
int b;
#if var > 8
int c;
#endif
}
This will work.
'#if' is a compiler directive (pre-processor directive). if statement on the other hand is runtime statement.
Other than this there is no other way!
int main()
{
int var = 10;
if(var>10){
struct example{
int a;
int b;
int c;
};
}else {
struct example{
int a;
int b;
};
}
cout<<"Hello World";
return 0;
}
There are multiple ways to address your problem one way of achieving is shown.
We cannot add if Statement in the Structure.
Related
How to pass enum in a scope to another as function argument? As this is failing:
enum class L;
struct TestClass
{
void foo(L n)
{
int v = static_cast<int>(n);
int r[v] = { 9 };
cout << "\n" << v << "\n";
}
};
int main()
{
enum class L : int
{
A, B, C, D
};
TestClass main;
main.foo(L::D);
return 0;
}
error: cannot convert ‘main()::L’ to ‘L’
80 | main.foo(L::D);
| ~~~^
| |
| main()::L
How to solve this (in exact place, not move enum to a scope else) ?
How to solve this (in the exact place, not move enum to a scope else)?
Cast the enum while passing as a parameter.
main.foo(static_cast<int>(L::D));
Then your member function would be
void foo(int n)
{
std::vector<int> r(n, 9); // used `std::vector` instead of VLA
std::cout << "\n" << n << "\n";
}
(See sample code)
Note that the VLAs are not part of standard C++. Read more in the following post:
Why aren't variable-length arrays part of the C++ standard?
Prefer using std::vector as shown in the above code sample.
In a nutshell, the problem is that you have an enum that you want to use in two places. To me, the most natural solution to this is to put the enum in its own header file and use it where it is required.
// my_enum.h
#pragma once
enum class L : int {
A, B, C, D
};
// TestClass.h
#pragma once
// Can forward declare L so long as we define the functions in the same cpp
// If original enum is in a namespace it needs to be forward declared in the same namespace
enum class L;
struct TestClass {
void foo(L n);
};
// TestClass.cpp
#include "TestClass.h"
#include "my_enum.h"
void TestClass::foo(L n)
{
// do stuff with n
}
// main.cpp
#include "TestClass.h"
#include "my_enum.h"
int main(){
TestClass main;
main.foo(L::D);
return 0;
}
How to solve this (in exact place, not move enum to a scope else) ?
I'm conscious that I've answered the question in a way you did not want, but I do not see why you wouldn't want to put the enum in its own file. Avoiding this will lead to problems at some point. The consequence of JeJo's solution is that you could pass any old integer in to foo() - it is essentially decoupled from the enum. If the integer value is supposed to originate from the enum L: 1) it isn't obvious from the function signature and 2) it is prone to misuse i.e. someone passing in a value they shouldn't.
If putting the enum in its own header file is an unacceptable solution, I'd be interested to know why.
I want to put constants in a struct, but compiler generates error that ";" is missing at the "=".
struct {
int aaa=111; // error: "expected ; at end of declaration list"
} blah;
Did you try maybe:
int aaa{111};
And if you need int as a constant you should probably include the const keyword.
const int aaa{111};
You can't initialize at the time of defining the structure in Obj-C. Initialization is possible at the time of creating instance shown as below.
struct Employee {
int idNumber;
int age;
};
// create instance
struct Employee emp1;
emp1.idNumber=12345;
emp1.age = 25;
If you're using Objective-C, in an .h file add something like:
extern const struct MyStruct {
int aaa;
} MyStruct;
In the .m file:
const struct MyStruct MyStruct = {
.aaa = 1
};
#import the .h file and use the struct in your code like this:
if (someInteger == MyStruct.aaa) ...
I am working on a feature, the code changes of which need to be guarded by checking registry keys. In .cpp files, I can simply check if the registry key is on or not and subsequently add the code changes. Here's an example:
bool isRegistryKeyOn = SomeMethodToCheckRegistryKey();
if(isRegistryKeyOn)
{
// New code goes here..
}
else
{
// Older one's here..
}
Now, I am facing a problem during changes in the header file. Suppose the header contains the following declarations:
class SomeClass
{
long var;
...
};
typedef int A;
And as part of the feature, I need this:
class SomeClass
{
long long var;
...
};
typedef int A;
typedef long long B;
How can I get around this requirement? All solutions, including the out-of-the-box ones are welcome!
Are you hoping to avoid changing the type in multiple places?
You're already using typedefs, why don't you nest them:
typedef long long T;
class SomeClass
{
T var;
//...
};
typedef int A;
typedef T B;
Any work around to make the below code work? it currently give the following error:
error: too many arguments provided to function-like macro invocation
X({1,2,3});
^
code:
#include <stdio.h>
#define X(a) a,
int main()
{
mystruct = X({1,2,3}));
}
I tried something with templates but so far I know (I'm a bit new to C++) templates aren't "powerful" enough to implement something like the X macro. As you may already noticied, what I'm looking for is implement something like the X macro. Others ideas to do this are very welcome too as long as everything is know at compile-time.
This does the trick:
#define X(...) __VA_ARGS__
struct mystruct {
int a,b,c;
};
int main() {
mystruct s = X({1,2,3});
}
Or as a variation:
#define X(...) {__VA_ARGS__}
struct mystruct {
int a,b,c;
};
int main() {
mystruct s = X(1,2,3);
}
In one of the SO thread, I had seen a usage of unnamed struct acting as a placeholder for multiple variables of different types inside for loop:
For example:
for(struct {
int i;
double d;
char c;
} obj = { 1, 2.2, 'c' };
obj.i < 10;
++obj.i)
{
...
}
This compiles fine with g++.
Is this a standard C++03 syntax?
You can use an unnamed struct anywhere you can use a struct - the only difference is that it doesn't get a name that can be used somewhere else. You can declare a new type anywhere you can use a type, pretty much. It may not be particularly meaningful to do so in most places, but that's another matter.
I wouldn't exactly recommend this, other than in very special cases, but it's valid.
Below code will work in C++ (g++ 5.4.0).
http://rextester.com/ELWLF59792
//g++ 5.4.0
#include <iostream>
#include <stdio.h>
int main()
{
int i = 0;
for(struct st{ int a[9]; }t;i<3;i++)
printf("%d\n", t.a);
}
And below code will work in C (gcc 5.4.0).
//gcc 5.4.0
#include <stdio.h>
int main()
{
int i = 0;
struct st{ int a[9]; }t;
for(;i<3;i++)
printf("%d\n", t.a);
}