+ 1

Sizeof compile time

Hi Refer code below: As sizeof is compile time operation , we will get output based on system on which it was compiled and not based on system on which it is running. Will there be any option to get this system bit (32 or 64) based on what code is executed ? int a = 5; sizeof(a) ==8 will also evaluated as 8==8 due to optimization. Correct ? https://sololearn.com/compiler-playground/cEHPmhvtnCw3/?ref=app

7th Dec 2024, 2:04 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
6 Antworten
+ 5
Ketan Lalcheta the executable gets compiled for either 32-bit or 64-bit. That is a determination that you make as the developer when you select the compiler (or compiler switches). Although a 32-bit program may run on a 64-bit machine, the exe does not get promoted at run time to be a 64-bit exe. Rather, the exe runs under 32-bit compatibility mode. It remains as a 32-bit program with all its limitations. Naturally, you cannot do the reverse and run a 64-bit program in a 32-bit environment.
7th Dec 2024, 5:03 PM
Brian
Brian - avatar
+ 3
My bad. Thanks for pointing it out . However, concern is about compile time evaluation. Assume executable built on 32 and ran on 64 bit.
7th Dec 2024, 4:44 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 3
Thank you for clarifying. I see that you edited the question and code. The 64-bit compiler would generate the equivalent of 'if (8==8)', and then optimize it to 'if (true)'. Furthermore the optimizer would make a second pass and eliminate the conditional branching p-code. It will simply execute the code under the if statement without the test. A 32-bit compiler will recognize it as 'if (4==8)' and optimize out all the code under the if statement. I looked up how to do this right, and found a better way: #if defined(__x86_64__) || defined(_M_X64) std::cout << "64-bit system\n"; #elif defined(__i386__) || defined(_M_IX86) std::cout << "32-bit system\n"; #endif
8th Dec 2024, 3:28 PM
Brian
Brian - avatar
+ 1
can you run code compiled for 64 bit on 32 bit machine? 32 can run on 64, but the other way around?
7th Dec 2024, 3:06 PM
Bob_Li
Bob_Li - avatar
+ 1
the value would probably be wrong for 64 bit, but it would probably only result in unoptimized resource use.
7th Dec 2024, 4:47 PM
Bob_Li
Bob_Li - avatar
+ 1
Thanks Brian. I am concerned about compiler doing optimization. I got it that 32 bit exe will remain 32 bit on 64 bit system.. What my worry is about below line from code: size_t size = sizeof(void*); if (size==8) so, these two might be replaced by below on 32 bit system due to compiler optimization: size_t size = sizeof(void*); if (true) hence , on each system be it 32 or 64, output will be same that is system is 64.
8th Dec 2024, 6:37 AM
Ketan Lalcheta
Ketan Lalcheta - avatar