473,698 Members | 2,747 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Integer multiplication truncation

The following code executes as I would expect on gcc:

#include <inttypes.h>
#include <stdio.h>

int main(int argc, char **argv){
uint16_t apa = 10000;
uint16_t kaka = 7000;
uint32_t mazarin;

mazarin = apa*kaka;
printf("%lu \n",mazarin);
return 0;
}

I.e. it will print out the value 70000000. However, when I compile
this another compiler the result is truncated and I have to modify the
code to the following to make it run:

#include <inttypes.h>
#include <stdio.h>

int main(int argc, char **argv){
uint16_t apa = 10000;
uint16_t kaka = 7000;
uint32_t mazarin;

mazarin = (uint32_t)apa*k aka;
printf("%lu \n",mazarin);
return 0;
}
Could anybody explain this? Is this due to C99 improvements regarding
integer overflow? Is there any predefined macro one could use to
determine this special case?

(Note: The extended types in inttypes.h were added for the second
compiler.)
Regards
/Michael
Feb 2 '08 #1
4 3800
Mamluk Caliph wrote:
I think I'm starting to understand and I can verify that an int type
on my GNU system is indeed 32 bits. I added the following line:

printf("%d %d %d %d
\n",sizeof(apa) ,sizeof(kaka),s izeof(mazarin), sizeof(int));

which will output: 2 2 4 4

So if I understand this correctly, the result of an integer
multiplication is always an int no matter of the type of the operands?
Or does it mean that both operands are always up-casted to an int
before the operation?
The type of the product is the type of the promoted operands. First, the
individual operands undergo default integer promotion, which would make
each at least the size of an int. If either operand has greater rank than
int, the other operand is promoted to that type and the result is also that
type.
What would happen if one of the operands would be 64 bits and the
values such that the result exceeds MAX_INT?
If the product of integer types is greater than can be expressed in the
resulting type, the value of the result depends on whether the resulting
type is signed or unsigned. If unsigned, the lower bits of the product are
kept. If the resulting type is signed, the result is undefined by the C
Standard.

--
Thad
Feb 2 '08 #2
Mamluk Caliph <ma***********@ gmail.comwrites :
The following code executes as I would expect on gcc:

#include <inttypes.h>
#include <stdio.h>

int main(int argc, char **argv){
uint16_t apa = 10000;
uint16_t kaka = 7000;
uint32_t mazarin;

mazarin = apa*kaka;
printf("%lu \n",mazarin);
return 0;
}

I.e. it will print out the value 70000000. However, when I compile
this another compiler the result is truncated and I have to modify the
code to the following to make it run:
[snip]

The types uint16_t and uint32_t are declared in <stdint.h>, not in
<inttypes.h>. It happens that <inttypes.hincl udes <stdint.h>, which
is why your program compiles, but the purpose of <inttypes.his to
define format conversions for use with the *printf and *scanf
functions.

If you just want the types, you should include <stdint.hrath er than
<inttypes.h>.

But the macros in <inttypes.har e one possible solution to your
problem. The trouble, IMHO, is that they're ugly. For example, your
printf call would be:

printf("%" PRIu32 "\n", mazarin);

Another solution is to convert the value to a type for which you know
the format. Since unsigned long is guaranteed to be a least 32 bits,
you can safely use "%lu" *if* you explicitly convert the value:

printf("%lu\n", (unsigned long)mazarin);

For wider types you might need to use "%zd" or "%zu" with intmax_t or
uintmax_t, defined in <stdint.h-- but only if your printf
implementation supports them (not all do).

--
Keith Thompson (The_Other_Keit h) <ks***@mib.or g>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Feb 2 '08 #3
Mamluk Caliph <ma***********@ gmail.comwrites :
[...]
By the way, I tried defining my own types and thought I could do
something as follows:

#if sizeof(int)==4
typedef int myInt32_t;
#endif

This results in a compilation error `missing binary operator before
token "("`, why is that? I thought sizof was just a macro.
[...]

No, sizeof is a built-in unary operator. (Its symbol happens to be a
keyword rather than a punctuation symbol.) The preprocessor doesn't
the "sizeof" or "int" keywords, so you can't use "sizeof(int )" in a
"#if" directive.

You can use the macros defined in <limits.hin preprocessor
directives, though, and since these specify the ranges that the types
can represent rather than the sizes of their representations , they
might be more appropriate.

--
Keith Thompson (The_Other_Keit h) <ks***@mib.or g>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Feb 2 '08 #4
On Sat, 02 Feb 2008 12:58:31 -0800, Keith Thompson wrote:
The types uint16_t and uint32_t are declared in <stdint.h>, not in
<inttypes.h>. It happens that <inttypes.hincl udes <stdint.h>, which
is why your program compiles, but the purpose of <inttypes.his to
define format conversions for use with the *printf and *scanf functions.
No, the purpose of <inttypes.his to define format specifiers for the
*printf and *scanf functions, as well as to provide the typedefs that
these format specifiers are meant to be used with. <inttypes.his the
historical header that C99 adopted and extended.
If you just want the types, you should include <stdint.hrath er than
<inttypes.h>.
<stdint.his a new invention in C99 intended to provide a subset of the
features of <inttypes.hth at can be required by freestanding
implementations (possibly lacking standard I/O). It incidentally happens
to have a possible benefit even for hosted implementations , but that
doesn't mean there's anything wrong with using <inttypes.h>.
Feb 2 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
8015
by: Christopher Dyken | last post by:
Hi group, I'm trying to implement two routines to handle 32x32-bits and 64x64-bits signed integer multiplication on a 32 bits machine in C. It easy to find descriptions of non-signed multiplication, however, I haven't found any good descriptions for the signed counterpart. Does any of you have a good reference for this topic? Thanks in advance,
20
9151
by: GS | last post by:
The stdint.h header definition mentions five integer categories, 1) exact width, eg., int32_t 2) at least as wide as, eg., int_least32_t 3) as fast as possible but at least as wide as, eg., int_fast32_t 4) integer capable of holding a pointer, intptr_t 5) widest integer in the implementation, intmax_t Is there a valid motivation for having both int_least and int_fast?
25
521
by: bruce.james.lee | last post by:
hi i have a problem with integer subtraction in C. printf("%d", c < (a - b)); a is got from a #define and is 0x80000000 and b is got from input and is also 0x80000000. c is ffffffff (-1). Now, this should print 1 (true) but it prints 0! If I modify this to d = c < (a - b);
25
6250
by: junky_fellow | last post by:
Is there any way by which the overflow during addition of two integers may be detected ? eg. suppose we have three unsigned integers, a ,b, c. we are doing a check like if ((a +b) > c) do something;
40
2793
by: Robert Seacord | last post by:
The CERT/CC has released a beta version of a secure integer library for the C Programming Language. The library is available for download from the CERT/CC Secure Coding Initiative web page at: http://www.cert.org/secure-coding/ The purpose of this library is to provide a collection of utility functions that can assist software developers in writing C programs that are free from common integer problems such as integer overflow, integer...
31
3118
by: Pesso | last post by:
What happens if you multiple two integers and the result overflows the MAX_INT in C? Is there a way to trap the condition when it happens?
2
1832
by: pankajit09 | last post by:
The maximum digit without truncation is 15 in EXCEL. How to avoid this truncation ?
14
5160
by: Default User | last post by:
Hi, If I have three 64 bit integers and I want to do this operation on them: x*y/z Lets say that what we are multiplying by (y) is offset by what we are dividing by (z) so that the final answer will fit in a 64-bit integer. Let me simplify it by using unsigned chars (8 bits):
6
3393
by: joegao1 | last post by:
can anyone help here? I am working on an embedded system with a C-like programming language, therefore floating point operation is not allowed (because it is time consuming), and floating point variable has to be represented by integer variable, with F stands for the length of bits representing the fractional part. e.g. value 4.5 with F=5 is represent by 10010000 (where the higher 3 bits representing integer value, and the lower 5...
0
8611
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9170
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8904
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8876
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7741
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4372
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4624
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.